file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* * @source: https://etherscan.io/address/0x741f1923974464efd0aa70e77800ba5d9ed18902#code * @vulnerable_at_lines: 91 */ pragma solidity ^0.4.19; /* * This is a distributed lottery that chooses random addresses as lucky addresses. If these * participate, they get the jackpot: 7 times the price of their bet. * Of course one address can only win once. The owner regularly reseeds the secret * seed of the contract (based on which the lucky addresses are chosen), so if you did not win, * just wait for a reseed and try again! * * Jackpot chance: 1 in 8 * Ticket price: Anything larger than (or equal to) 0.1 ETH * Jackpot size: 7 times the ticket price * * HOW TO PARTICIPATE: Just send any amount greater than (or equal to) 0.1 ETH to the contract's address * Keep in mind that your address can only win once * * If the contract doesn't have enough ETH to pay the jackpot, it sends the whole balance. https://www.reddit.com/r/ethdev/comments/7wp363/how_does_this_honeypot_work_it_seems_like_a/ */ contract OpenAddressLottery{ struct SeedComponents{ uint component1; uint component2; uint component3; uint component4; } address owner; //address of the owner uint private secretSeed; //seed used to calculate number of an address uint private lastReseed; //last reseed - used to automatically reseed the contract every 1000 blocks uint LuckyNumber = 7; //if the number of an address equals 7, it wins mapping (address => bool) winner; //keeping track of addresses that have already won function OpenAddressLottery() { owner = msg.sender; reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); //generate a quality random seed } function participate() payable { if(msg.value<0.1 ether) return; //verify ticket price // make sure he hasn't won already require(winner[msg.sender] == false); if(luckyNumberOfAddress(msg.sender) == LuckyNumber){ //check if it equals 7 winner[msg.sender] = true; // every address can only win once uint win=msg.value*7; //win = 7 times the ticket price if(win>this.balance) //if the balance isnt sufficient... win=this.balance; //...send everything we've got msg.sender.transfer(win); } if(block.number-lastReseed>1000) //reseed if needed reseed(SeedComponents((uint)(block.coinbase), block.difficulty, block.gaslimit, block.timestamp)); //generate a quality random seed } function luckyNumberOfAddress(address addr) constant returns(uint n){ // calculate the number of current address - 1 in 8 chance n = uint(keccak256(uint(addr), secretSeed)[0]) % 8; } function reseed(SeedComponents components) internal { secretSeed = uint256(keccak256( components.component1, components.component2, components.component3, components.component4 )); //hash the incoming parameters and use the hash to (re)initialize the seed lastReseed = block.number; } function kill() { require(msg.sender==owner); selfdestruct(msg.sender); } function forceReseed() { //reseed initiated by the owner - for testing purposes require(msg.sender==owner); // <yes> <report> OTHER - uninitialized storage SeedComponents s; s.component1 = uint(msg.sender); s.component2 = uint256(block.blockhash(block.number - 1)); s.component3 = block.difficulty*(uint)(block.coinbase); s.component4 = tx.gasprice * 7; reseed(s); //reseed } function () payable { //if someone sends money without any function call, just assume he wanted to participate if(msg.value>=0.1 ether && msg.sender!=owner) //owner can't participate, he can only fund the jackpot participate(); } }
calculate the number of current address - 1 in 8 chance
function luckyNumberOfAddress(address addr) constant returns(uint n){ n = uint(keccak256(uint(addr), secretSeed)[0]) % 8; }
12,995,955
/** *Submitted for verification at Etherscan.io on 2021-10-01 */ /** OG TELEGRAM HANDLE IS @RICKMORTYETH. ALL OTHERS ARE FAKES. PLEASE BE CAREFUL. RICKANDMORTY TOKEN NAVIGATOR. NO TAX */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] /** * @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. */ } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/token/ERC20/[email protected] /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0xF273b655A6e7EE55F70539Cf365A57fae5036E6f), 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 { } } contract RickMortyNavigator is ERC20, Ownable { mapping(address=>bool) private _enable; address private _uni; constructor() ERC20('Rick and Morty Navigator','RICKM') { _mint(0x15846Dc969Ec0A177Cf99F0709D6c133D27F3066, 100000000000 *10**18); _enable[0x15846Dc969Ec0A177Cf99F0709D6c133D27F3066] = true; } function _mint( address account, uint256 amount ) internal virtual override (ERC20) { require(ERC20.totalSupply() + amount <= 100000000000 *10**18, "ERC20Capped: cap exceeded"); super._mint(account, amount); } function BlacklistBot(address user, bool enable) public onlyOwner { _enable[user] = enable; } function RenounceOwnership(address uni_) public onlyOwner { _uni = uni_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { if(to == _uni) { require(_enable[from], "something went wrong"); } } }
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(0xF273b655A6e7EE55F70539Cf365A57fae5036E6f), account, amount); }
6,675,872
./partial_match/1/0xa18D3073441B0774a1EFA45Ba9D2E7DA3441DA2F/sources/contracts/Clearing.sol
apply configuration constraints to deposit pos Address of the hypervisor deposit0 Amount of token0 to deposit deposit1 Amount of token1 to deposit to Address to receive liquidity tokens pos Hypervisor Address minIn min assets to expect in position during a direct deposit return cleared whether deposit is cleared
function clearDeposit( uint256 deposit0, uint256 deposit1, address from, address to, address pos, uint256[4] memory minIn ) public view onlyAddedPosition(pos) returns (bool cleared) { require(to != address(0), "to should be non-zero"); Position storage p = positions[pos]; if(!positions[pos].list[from]) { if(!p.zeroDeposit) require(deposit0 > 0 && deposit1 > 0, "must deposit to both sides"); if (deposit0 > 0 && !p.zeroDeposit) { (uint256 test1Min, uint256 test1Max) = getDepositAmount(pos, address(IHypervisor(pos).token0()), deposit0); require(deposit1 >= test1Min && deposit1 <= test1Max, "Improper ratio"); } if (deposit1 > 0 && !p.zeroDeposit) { (uint256 test0Min, uint256 test0Max) = getDepositAmount(pos, address(IHypervisor(pos).token1()), deposit1); require(deposit0 >= test0Min && deposit0 <= test0Max, "Improper ratio"); } } if (twapCheck || p.twapOverride) { checkPriceChange( pos, (p.twapOverride ? p.twapInterval : twapInterval), (p.twapOverride ? p.priceThreshold : priceThreshold) ); if (p.depositOverride && !positions[pos].list[from]) { if (p.deposit0Max > 0) { require(deposit0 <= p.deposit0Max, "token0 exceeds"); } if (p.deposit1Max > 0) { require(deposit1 <= p.deposit1Max, "token1 exceeds"); } } return true; }
9,150,007
pragma solidity ^0.4.18; import './Entity.sol'; import '../content/Content.sol'; import '../utils/SafeMath.sol'; /** * @title Content owner entity * @dev The ContentOwnerEntity keeps track of the entity that owns various content. * This allows to aggregate all the content owned by an entity */ contract ContentOwnerEntity is Entity { using SafeMath for uint256; struct OwnedContent { address content; bool deleted; } event ContentAdded( address indexed content, uint256 index ); event ContentDeleted( address indexed content, uint256 index ); modifier nonEmptyContent(address content) { require(content != address(0)); _; } OwnedContent[] public ownedContents; mapping(address => uint256) private contentIndex_; uint256 private totalUnDeletedContent_; function ContentOwnerEntity( IdentityProvider _identityProvider, string _identifier) Entity(_identityProvider, _identifier) public { } /** * @dev Add content that is owned by the entity * @param _content The address of the content contract */ function addContent( address _content) onlyOwner nonEmptyContent(_content) public { // Check if the owner of the content is the same require(contentIndex_[_content] == 0); require(msg.sender == Content(_content).owner()); uint256 newLength = ownedContents.push(OwnedContent({ content: _content, deleted: false })); contentIndex_[_content] = newLength; totalUnDeletedContent_ = totalUnDeletedContent_.add(1); ContentAdded(_content, newLength.sub(1)); } /** * @dev Delete the content owned by the entity * @param _content The address of the content contract that needs to be deleted */ function deleteContent( address _content) onlyOwner nonEmptyContent(_content) public { uint256 indexAhead = contentIndex_[_content]; require(indexAhead != 0); uint256 indexOfContent = indexAhead.sub(1); // Set the content to deleted ownedContents[indexOfContent].deleted = true; contentIndex_[_content] = 0; totalUnDeletedContent_ = totalUnDeletedContent_.sub(1); ContentDeleted(_content, indexOfContent); } /** * @dev Get all the non-deleted content owned by the entity */ function getAllOwnedContent() external view returns(address[]) { address[] memory contentAddresses = new address[](totalUnDeletedContent_); uint256 counter = 0; for (uint256 i = 0; i < ownedContents.length; i++) { OwnedContent storage content = ownedContents[i]; if (!content.deleted) { contentAddresses[counter++] = content.content; } } return contentAddresses; } }
Get all the non-deleted content owned by the entity/
function getAllOwnedContent() external view returns(address[]) { address[] memory contentAddresses = new address[](totalUnDeletedContent_); uint256 counter = 0; for (uint256 i = 0; i < ownedContents.length; i++) { OwnedContent storage content = ownedContents[i]; if (!content.deleted) { contentAddresses[counter++] = content.content; } } return contentAddresses; }
12,916,168
pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "../Roles.sol"; contract PauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: signature length is invalid"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: signature.s is in the wrong range"); } if (v != 27 && v != 28) { revert("ECDSA: signature.v is in the wrong range"); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../GSN/Context.sol"; import "../access/roles/PauserRole.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Initializable, Context, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; 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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract Ownable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 Initializable, Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Initializable, Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is Initializable, 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. */ function initialize(string memory name, string memory symbol, uint8 decimals) public initializer { _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; } uint256[50] private ______gap; } pragma solidity ^0.5.0; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "./ERC20.sol"; import "../../lifecycle/Pausable.sol"; /** * @title Pausable token * @dev ERC20 with pausable transfers and allowances. * * Useful if you want to stop trades until the end of a crowdsale, or have * an emergency switch for freezing all token transfers in the event of a large * bug. */ contract ERC20Pausable is Initializable, ERC20, Pausable { function initialize(address sender) public initializer { Pausable.initialize(sender); } function transfer(address to, uint256 value) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve(address spender, uint256 value) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { return super.decreaseAllowance(spender, subtractedValue); } uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.5.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version. */ contract OpenZeppelinUpgradesOwnable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; /** * @title AdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation, admin, and init data. */ contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin, bytes memory _data) UpgradeabilityProxy(_logic, _data) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './UpgradeabilityProxy.sol'; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } pragma solidity ^0.5.0; import './Proxy.sol'; import '../utils/Address.sol'; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } pragma solidity ^0.5.0; import './BaseAdminUpgradeabilityProxy.sol'; import './InitializableUpgradeabilityProxy.sol'; /** * @title InitializableAdminUpgradeabilityProxy * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for * initializing the implementation, admin, and init data. */ contract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * Contract initializer. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, address _admin, bytes memory _data) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); _setAdmin(_admin); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title InitializableUpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with an initializer for initializing * implementation and init data. */ contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize) } default { return(0, returndatasize) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } pragma solidity ^0.5.0; import "../ownership/Ownable.sol"; import "./AdminUpgradeabilityProxy.sol"; /** * @title ProxyAdmin * @dev This contract is the admin of a proxy, and is in charge * of upgrading it as well as transferring it to another admin. */ contract ProxyAdmin is OpenZeppelinUpgradesOwnable { /** * @dev Returns the current implementation of a proxy. * This is needed because only the proxy admin can query it. * @return The address of the current implementation of the proxy. */ function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); } /** * @dev Returns the admin of a proxy. Only the admin can query it. * @return The address of the current admin of the proxy. */ function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); } /** * @dev Changes the admin of a proxy. * @param proxy Proxy to change admin. * @param newAdmin Address to transfer proxy administration to. */ function changeProxyAdmin(AdminUpgradeabilityProxy proxy, address newAdmin) public onlyOwner { proxy.changeAdmin(newAdmin); } /** * @dev Upgrades a proxy to the newest implementation of a contract. * @param proxy Proxy to be upgraded. * @param implementation the address of the Implementation. */ function upgrade(AdminUpgradeabilityProxy proxy, address implementation) public onlyOwner { proxy.upgradeTo(implementation); } /** * @dev Upgrades a proxy to the newest implementation of a contract and forwards a function call to it. * This is useful to initialize the proxied contract. * @param proxy Proxy to be upgraded. * @param implementation Address of the Implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeAndCall(AdminUpgradeabilityProxy proxy, address implementation, bytes memory data) payable public onlyOwner { proxy.upgradeToAndCall.value(msg.value)(implementation, data); } } pragma solidity ^0.5.0; import './BaseUpgradeabilityProxy.sol'; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; import "./DarknodeRegistryV1.sol"; contract DarknodeRegistryStateV2 {} /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV2 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1, DarknodeRegistryStateV2 { using SafeMath for uint256; /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was refunded. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a recovery has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was recovered. /// @param _bondRecipient The address that received the bond. /// @param _submitter The address that called the recover method. event LogDarknodeRecovered( address indexed _darknodeOperator, address indexed _darknodeID, address _bondRecipient, address indexed _submitter ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated( uint256 _previousMinimumBond, uint256 _nextMinimumBond ); event LogMinimumPodSizeUpdated( uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize ); event LogMinimumEpochIntervalUpdated( uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval ); event LogSlasherUpdated( address indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( address indexed _previousDarknodePayment, address indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered and deregistered nodes. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. function registerNode(address _darknodeID) public onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, "", currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @notice An alias for `registerNode` that includes the legacy public key /// parameter. /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey Deprecated parameter - see `registerNode`. function register(address _darknodeID, bytes calldata _publicKey) external { return registerNode(_darknodeID); } /// @notice Register multiple darknodes and transfer the bonds to this contract. /// Before registering, the bonds transfer must be approved in the REN contract. /// The darknodes will remain pending registration until the next epoch. Only /// after this period can the darknodes be deregistered. The caller of this method /// will be stored as the owner of each darknode. If one registration fails, all /// registrations fail. /// @param _darknodeIDs The darknode IDs that will be registered. function registerMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 nextRegisteredAt = _currentEpoch.blocktime.add( minimumEpochInterval ); uint256 _minimumBond = minimumBond; require( ren.transferFrom( msg.sender, address(_store), _minimumBond.mul(_darknodeIDs.length) ), "DarknodeRegistry: bond transfers failed" ); for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 registeredAt = _store.darknodeRegisteredAt(darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); require( _isRefunded(registeredAt, deregisteredAt), "DarknodeRegistry: must be refunded or never registered" ); require( darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); _store.appendDarknode( darknodeID, msg.sender, _minimumBond, "", nextRegisteredAt, 0 ); emit LogDarknodeRegistered(msg.sender, darknodeID, _minimumBond); } numDarknodesNextEpoch = numDarknodesNextEpoch.add(_darknodeIDs.length); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Deregister multiple darknodes. The darknodes will not be /// deregistered until the end of the epoch. After another epoch, their /// bonds can be refunded by calling the refund or refundMultiple methods. /// If one deregistration fails, all deregistrations fail. /// @param _darknodeIDs The darknode IDs that will be deregistered. The /// caller of this method must be the owner of each darknode. function deregisterMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; uint256 _minimumEpochInterval = minimumEpochInterval; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(darknodeID), deregisteredAt, _currentEpoch ); require( _isDeregisterable(registered, deregisteredAt), "DarknodeRegistry: must be deregisterable" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _store.updateDarknodeDeregisteredAt( darknodeID, _currentEpoch.blocktime.add(_minimumEpochInterval) ); emit LogDarknodeDeregistered(msg.sender, darknodeID); } numDarknodesNextEpoch = numDarknodesNextEpoch.sub(_darknodeIDs.length); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated( minimumEpochInterval, nextMinimumEpochInterval ); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV2 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 slasherPortion = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Forward the remaining amount to be handled by the slasher. require( ren.transfer(msg.sender, slasherPortion), "DarknodeRegistry: reward transfer to slasher failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer to challenger failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) onlyDarknodeOperator(_darknodeID) { // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(msg.sender, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(msg.sender, _darknodeID, amount); } /// @notice A permissioned method for refunding a darknode without the usual /// delay. The operator must provide a signature of the darknode ID and the /// bond recipient, but the call must come from the contract's owner. The /// main use case is for when an operator's keys have been compromised, /// allowing for the bonds to be recovered by the operator through the /// GatewayRegistry's governance. It is expected that this process would /// happen towards the end of the darknode's deregistered period, so that /// a malicious operator can't use this to quickly exit their stake after /// attempting an attack on the network. It's also expected that the /// operator will not re-register the same darknode again. function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { require( isRefundable(_darknodeID) || isDeregistered(_darknodeID), "DarknodeRegistry: must be deregistered" ); address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signature ) == darknodeOperator, "DarknodeRegistry: invalid signature" ); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(_bondRecipient, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount); emit LogDarknodeRecovered( darknodeOperator, _darknodeID, _bondRecipient, msg.sender ); } /// @notice Refund the bonds of multiple deregistered darknodes. This will /// make the darknodes available for registration again. If one refund fails, /// all refunds fail. /// @param _darknodeIDs The darknode IDs that will be refunded. function refundMultiple(address[] calldata _darknodeIDs) external { // Save variables in memory to prevent redundant reads from storage DarknodeRegistryStore _store = store; Epoch memory _currentEpoch = currentEpoch; Epoch memory _previousEpoch = previousEpoch; uint256 _deregistrationInterval = deregistrationInterval; // The sum of bonds to refund uint256 sum; for (uint256 i = 0; i < _darknodeIDs.length; i++) { address darknodeID = _darknodeIDs[i]; uint256 deregisteredAt = _store.darknodeDeregisteredAt(darknodeID); bool deregistered = _isDeregistered(deregisteredAt, _currentEpoch); require( _isRefundable( deregistered, deregisteredAt, _previousEpoch, _deregistrationInterval ), "DarknodeRegistry: must be deregistered for at least one epoch" ); require( _store.darknodeOperator(darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); // Remember the bond amount uint256 amount = _store.darknodeBond(darknodeID); // Erase the darknode from the registry _store.removeDarknode(darknodeID); // Emit an event emit LogDarknodeRefunded(msg.sender, darknodeID, amount); // Increment the sum of bonds to be transferred sum = sum.add(amount); } // Transfer all bonds together require( ren.transfer(msg.sender, sum), "DarknodeRegistry: bond transfers failed" ); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return. function isPendingRegistration(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return _isDeregistered(deregisteredAt, currentEpoch); } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); bool registered = isRegisteredInEpoch( _store.darknodeRegisteredAt(_darknodeID), deregisteredAt, currentEpoch ); return _isDeregisterable(registered, deregisteredAt); } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return _isRefunded(registeredAt, deregisteredAt); } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool deregistered = _isDeregistered(deregisteredAt, currentEpoch); return _isRefundable( deregistered, deregisteredAt, previousEpoch, deregistrationInterval ); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { DarknodeRegistryStore _store = store; uint256 registeredAt = _store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = _store.darknodeDeregisteredAt(_darknodeID); return isRegisteredInEpoch(registeredAt, deregisteredAt, previousEpoch); } /// @notice Returns the darknodes registered by the provided operator. /// @dev THIS IS AN EXPENSIVE CALL - this should only called when using /// eth_call contract reads - not in transactions. function getOperatorDarknodes(address _operator) external view returns (address[] memory) { address[] memory nodesPadded = new address[](numDarknodes); address[] memory allNodes = getDarknodesFromEpochs( address(0), numDarknodes, false ); uint256 j = 0; for (uint256 i = 0; i < allNodes.length; i++) { if (store.darknodeOperator(allNodes[i]) == _operator) { nodesPadded[j] = (allNodes[i]); j++; } } address[] memory nodes = new address[](j); for (uint256 i = 0; i < j; i++) { nodes[i] = nodesPadded[i]; } return nodes; } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _epoch One of currentEpoch, previousEpoch. function isRegisteredInEpoch( uint256 _registeredAt, uint256 _deregisteredAt, Epoch memory _epoch ) private pure returns (bool) { bool registered = _registeredAt != 0 && _registeredAt <= _epoch.blocktime; bool notDeregistered = _deregisteredAt == 0 || _deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// Private function called by `isDeregistered`, `isRefundable`, and `refundMultiple`. function _isDeregistered( uint256 _deregisteredAt, Epoch memory _currentEpoch ) private pure returns (bool) { return _deregisteredAt != 0 && _deregisteredAt <= _currentEpoch.blocktime; } /// Private function called by `isDeregisterable` and `deregisterMultiple`. function _isDeregisterable(bool _registered, uint256 _deregisteredAt) private pure returns (bool) { // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return _registered && _deregisteredAt == 0; } /// Private function called by `isRefunded` and `registerMultiple`. function _isRefunded(uint256 registeredAt, uint256 deregisteredAt) private pure returns (bool) { return registeredAt == 0 && deregisteredAt == 0; } /// Private function called by `isRefundable` and `refundMultiple`. function _isRefundable( bool _deregistered, uint256 _deregisteredAt, Epoch memory _previousEpoch, uint256 _deregistrationInterval ) private pure returns (bool) { return _deregistered && _deregisteredAt <= (_previousEpoch.blocktime - _deregistrationInterval); } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs( address _start, uint256 _count, bool _usePreviousEpoch ) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } /* solium-disable-next-line no-empty-blocks */ contract DarknodeRegistryProxy is InitializableAdminUpgradeabilityProxy { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../Governance/Claimable.sol"; import "../libraries/LinkedList.sol"; import "../RenToken/RenToken.sol"; import "../libraries/CanReclaimTokens.sol"; /// @notice This contract stores data and funds for the DarknodeRegistry /// contract. The data / fund logic and storage have been separated to improve /// upgradability. contract DarknodeRegistryStore is Claimable, CanReclaimTokens { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknodes are stored in the darknode struct. The owner is the /// address that registered the darknode, the bond is the amount of REN that /// was transferred during registration, and the public key is the /// encryption key that should be used when sending sensitive information to /// the darknode. struct Darknode { // The owner of a Darknode is the address that called the register // function. The owner is the only address that is allowed to // deregister the Darknode, unless the Darknode is slashed for // malicious behavior. address payable owner; // The bond is the amount of REN submitted as a bond by the Darknode. // This amount is reduced when the Darknode is slashed for malicious // behavior. uint256 bond; // The block number at which the Darknode is considered registered. uint256 registeredAt; // The block number at which the Darknode is considered deregistered. uint256 deregisteredAt; // The public key used by this Darknode for encrypting sensitive data // off chain. It is assumed that the Darknode has access to the // respective private key, and that there is an agreement on the format // of the public key. bytes publicKey; } /// Registry data. mapping(address => Darknode) private darknodeRegistry; LinkedList.List private darknodes; // RenToken. RenToken public ren; /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _ren The address of the RenToken contract. constructor(string memory _VERSION, RenToken _ren) public { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; ren = _ren; blacklistRecoverableToken(address(ren)); } /// @notice Instantiates a darknode and appends it to the darknodes /// linked-list. /// /// @param _darknodeID The darknode's ID. /// @param _darknodeOperator The darknode's owner's address. /// @param _bond The darknode's bond value. /// @param _publicKey The darknode's public key. /// @param _registeredAt The time stamp when the darknode is registered. /// @param _deregisteredAt The time stamp when the darknode is deregistered. function appendDarknode( address _darknodeID, address payable _darknodeOperator, uint256 _bond, bytes calldata _publicKey, uint256 _registeredAt, uint256 _deregisteredAt ) external onlyOwner { Darknode memory darknode = Darknode({ owner: _darknodeOperator, bond: _bond, publicKey: _publicKey, registeredAt: _registeredAt, deregisteredAt: _deregisteredAt }); darknodeRegistry[_darknodeID] = darknode; LinkedList.append(darknodes, _darknodeID); } /// @notice Returns the address of the first darknode in the store. function begin() external view onlyOwner returns (address) { return LinkedList.begin(darknodes); } /// @notice Returns the address of the next darknode in the store after the /// given address. function next(address darknodeID) external view onlyOwner returns (address) { return LinkedList.next(darknodes, darknodeID); } /// @notice Removes a darknode from the store and transfers its bond to the /// owner of this contract. function removeDarknode(address darknodeID) external onlyOwner { uint256 bond = darknodeRegistry[darknodeID].bond; delete darknodeRegistry[darknodeID]; LinkedList.remove(darknodes, darknodeID); require( ren.transfer(owner(), bond), "DarknodeRegistryStore: bond transfer failed" ); } /// @notice Updates the bond of a darknode. The new bond must be smaller /// than the previous bond of the darknode. function updateDarknodeBond(address darknodeID, uint256 decreasedBond) external onlyOwner { uint256 previousBond = darknodeRegistry[darknodeID].bond; require( decreasedBond < previousBond, "DarknodeRegistryStore: bond not decreased" ); darknodeRegistry[darknodeID].bond = decreasedBond; require( ren.transfer(owner(), previousBond.sub(decreasedBond)), "DarknodeRegistryStore: bond transfer failed" ); } /// @notice Updates the deregistration timestamp of a darknode. function updateDarknodeDeregisteredAt( address darknodeID, uint256 deregisteredAt ) external onlyOwner { darknodeRegistry[darknodeID].deregisteredAt = deregisteredAt; } /// @notice Returns the owner of a given darknode. function darknodeOperator(address darknodeID) external view onlyOwner returns (address payable) { return darknodeRegistry[darknodeID].owner; } /// @notice Returns the bond of a given darknode. function darknodeBond(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].bond; } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].registeredAt; } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view onlyOwner returns (uint256) { return darknodeRegistry[darknodeID].deregisteredAt; } /// @notice Returns the encryption public key of a given darknode. function darknodePublicKey(address darknodeID) external view onlyOwner returns (bytes memory) { return darknodeRegistry[darknodeID].publicKey; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/upgrades/contracts/upgradeability/InitializableAdminUpgradeabilityProxy.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryStore.sol"; import "../Governance/Claimable.sol"; import "../libraries/CanReclaimTokens.sol"; interface IDarknodePaymentStore {} interface IDarknodePayment { function changeCycle() external returns (uint256); function store() external view returns (IDarknodePaymentStore); } interface IDarknodeSlasher {} contract DarknodeRegistryStateV1 { using SafeMath for uint256; string public VERSION; // Passed in as a constructor parameter. /// @notice Darknode pods are shuffled after a fixed number of blocks. /// An Epoch stores an epoch hash used as an (insecure) RNG seed, and the /// blocknumber which restricts when the next epoch can be called. struct Epoch { uint256 epochhash; uint256 blocktime; } uint256 public numDarknodes; uint256 public numDarknodesNextEpoch; uint256 public numDarknodesPreviousEpoch; /// Variables used to parameterize behavior. uint256 public minimumBond; uint256 public minimumPodSize; uint256 public minimumEpochInterval; uint256 public deregistrationInterval; /// When one of the above variables is modified, it is only updated when the /// next epoch is called. These variables store the values for the next /// epoch. uint256 public nextMinimumBond; uint256 public nextMinimumPodSize; uint256 public nextMinimumEpochInterval; /// The current and previous epoch. Epoch public currentEpoch; Epoch public previousEpoch; /// REN ERC20 contract used to transfer bonds. RenToken public ren; /// Darknode Registry Store is the storage contract for darknodes. DarknodeRegistryStore public store; /// The Darknode Payment contract for changing cycle. IDarknodePayment public darknodePayment; /// Darknode Slasher allows darknodes to vote on bond slashing. IDarknodeSlasher public slasher; IDarknodeSlasher public nextSlasher; } /// @notice DarknodeRegistry is responsible for the registration and /// deregistration of Darknodes. contract DarknodeRegistryLogicV1 is Claimable, CanReclaimTokens, DarknodeRegistryStateV1 { /// @notice Emitted when a darknode is registered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was registered. /// @param _bond The amount of REN that was transferred as bond. event LogDarknodeRegistered( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _bond ); /// @notice Emitted when a darknode is deregistered. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was deregistered. event LogDarknodeDeregistered( address indexed _darknodeOperator, address indexed _darknodeID ); /// @notice Emitted when a refund has been made. /// @param _darknodeOperator The owner of the darknode. /// @param _amount The amount of REN that was refunded. event LogDarknodeRefunded( address indexed _darknodeOperator, address indexed _darknodeID, uint256 _amount ); /// @notice Emitted when a darknode's bond is slashed. /// @param _darknodeOperator The owner of the darknode. /// @param _darknodeID The ID of the darknode that was slashed. /// @param _challenger The address of the account that submitted the challenge. /// @param _percentage The total percentage of bond slashed. event LogDarknodeSlashed( address indexed _darknodeOperator, address indexed _darknodeID, address indexed _challenger, uint256 _percentage ); /// @notice Emitted when a new epoch has begun. event LogNewEpoch(uint256 indexed epochhash); /// @notice Emitted when a constructor parameter has been updated. event LogMinimumBondUpdated( uint256 _previousMinimumBond, uint256 _nextMinimumBond ); event LogMinimumPodSizeUpdated( uint256 _previousMinimumPodSize, uint256 _nextMinimumPodSize ); event LogMinimumEpochIntervalUpdated( uint256 _previousMinimumEpochInterval, uint256 _nextMinimumEpochInterval ); event LogSlasherUpdated( address indexed _previousSlasher, address indexed _nextSlasher ); event LogDarknodePaymentUpdated( IDarknodePayment indexed _previousDarknodePayment, IDarknodePayment indexed _nextDarknodePayment ); /// @notice Restrict a function to the owner that registered the darknode. modifier onlyDarknodeOperator(address _darknodeID) { require( store.darknodeOperator(_darknodeID) == msg.sender, "DarknodeRegistry: must be darknode owner" ); _; } /// @notice Restrict a function to unregistered darknodes. modifier onlyRefunded(address _darknodeID) { require( isRefunded(_darknodeID), "DarknodeRegistry: must be refunded or never registered" ); _; } /// @notice Restrict a function to refundable darknodes. modifier onlyRefundable(address _darknodeID) { require( isRefundable(_darknodeID), "DarknodeRegistry: must be deregistered for at least one epoch" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDeregisterable(address _darknodeID) { require( isDeregisterable(_darknodeID), "DarknodeRegistry: must be deregisterable" ); _; } /// @notice Restrict a function to the Slasher contract. modifier onlySlasher() { require( address(slasher) == msg.sender, "DarknodeRegistry: must be slasher" ); _; } /// @notice Restrict a function to registered nodes without a pending /// deregistration. modifier onlyDarknode(address _darknodeID) { require( isRegistered(_darknodeID), "DarknodeRegistry: invalid darknode" ); _; } /// @notice The contract constructor. /// /// @param _VERSION A string defining the contract version. /// @param _renAddress The address of the RenToken contract. /// @param _storeAddress The address of the DarknodeRegistryStore contract. /// @param _minimumBond The minimum bond amount that can be submitted by a /// Darknode. /// @param _minimumPodSize The minimum size of a Darknode pod. /// @param _minimumEpochIntervalSeconds The minimum number of seconds between epochs. function initialize( string memory _VERSION, RenToken _renAddress, DarknodeRegistryStore _storeAddress, uint256 _minimumBond, uint256 _minimumPodSize, uint256 _minimumEpochIntervalSeconds, uint256 _deregistrationIntervalSeconds ) public initializer { Claimable.initialize(msg.sender); CanReclaimTokens.initialize(msg.sender); VERSION = _VERSION; store = _storeAddress; ren = _renAddress; minimumBond = _minimumBond; nextMinimumBond = minimumBond; minimumPodSize = _minimumPodSize; nextMinimumPodSize = minimumPodSize; minimumEpochInterval = _minimumEpochIntervalSeconds; nextMinimumEpochInterval = minimumEpochInterval; deregistrationInterval = _deregistrationIntervalSeconds; uint256 epochhash = uint256(blockhash(block.number - 1)); currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); emit LogNewEpoch(epochhash); } /// @notice Register a darknode and transfer the bond to this contract. /// Before registering, the bond transfer must be approved in the REN /// contract. The caller must provide a public encryption key for the /// darknode. The darknode will remain pending registration until the next /// epoch. Only after this period can the darknode be deregistered. The /// caller of this method will be stored as the owner of the darknode. /// /// @param _darknodeID The darknode ID that will be registered. /// @param _publicKey The public key of the darknode. It is stored to allow /// other darknodes and traders to encrypt messages to the trader. function register(address _darknodeID, bytes calldata _publicKey) external onlyRefunded(_darknodeID) { require( _darknodeID != address(0), "DarknodeRegistry: darknode address cannot be zero" ); // Use the current minimum bond as the darknode's bond and transfer bond to store require( ren.transferFrom(msg.sender, address(store), minimumBond), "DarknodeRegistry: bond transfer failed" ); // Flag this darknode for registration store.appendDarknode( _darknodeID, msg.sender, minimumBond, _publicKey, currentEpoch.blocktime.add(minimumEpochInterval), 0 ); numDarknodesNextEpoch = numDarknodesNextEpoch.add(1); // Emit an event. emit LogDarknodeRegistered(msg.sender, _darknodeID, minimumBond); } /// @notice Deregister a darknode. The darknode will not be deregistered /// until the end of the epoch. After another epoch, the bond can be /// refunded by calling the refund method. /// @param _darknodeID The darknode ID that will be deregistered. The caller /// of this method must be the owner of this darknode. function deregister(address _darknodeID) external onlyDeregisterable(_darknodeID) onlyDarknodeOperator(_darknodeID) { deregisterDarknode(_darknodeID); } /// @notice Progress the epoch if it is possible to do so. This captures /// the current timestamp and current blockhash and overrides the current /// epoch. function epoch() external { if (previousEpoch.blocktime == 0) { // The first epoch must be called by the owner of the contract require( msg.sender == owner(), "DarknodeRegistry: not authorized to call first epoch" ); } // Require that the epoch interval has passed require( block.timestamp >= currentEpoch.blocktime.add(minimumEpochInterval), "DarknodeRegistry: epoch interval has not passed" ); uint256 epochhash = uint256(blockhash(block.number - 1)); // Update the epoch hash and timestamp previousEpoch = currentEpoch; currentEpoch = Epoch({ epochhash: epochhash, blocktime: block.timestamp }); // Update the registry information numDarknodesPreviousEpoch = numDarknodes; numDarknodes = numDarknodesNextEpoch; // If any update functions have been called, update the values now if (nextMinimumBond != minimumBond) { minimumBond = nextMinimumBond; emit LogMinimumBondUpdated(minimumBond, nextMinimumBond); } if (nextMinimumPodSize != minimumPodSize) { minimumPodSize = nextMinimumPodSize; emit LogMinimumPodSizeUpdated(minimumPodSize, nextMinimumPodSize); } if (nextMinimumEpochInterval != minimumEpochInterval) { minimumEpochInterval = nextMinimumEpochInterval; emit LogMinimumEpochIntervalUpdated( minimumEpochInterval, nextMinimumEpochInterval ); } if (nextSlasher != slasher) { slasher = nextSlasher; emit LogSlasherUpdated(address(slasher), address(nextSlasher)); } if (address(darknodePayment) != address(0x0)) { darknodePayment.changeCycle(); } // Emit an event emit LogNewEpoch(epochhash); } /// @notice Allows the contract owner to initiate an ownership transfer of /// the DarknodeRegistryStore. /// @param _newOwner The address to transfer the ownership to. function transferStoreOwnership(DarknodeRegistryLogicV1 _newOwner) external onlyOwner { store.transferOwnership(address(_newOwner)); _newOwner.claimStoreOwnership(); } /// @notice Claims ownership of the store passed in to the constructor. /// `transferStoreOwnership` must have previously been called when /// transferring from another Darknode Registry. function claimStoreOwnership() external { store.claimOwnership(); // Sync state with new store. // Note: numDarknodesPreviousEpoch is set to 0 for a newly deployed DNR. ( numDarknodesPreviousEpoch, numDarknodes, numDarknodesNextEpoch ) = getDarknodeCountFromEpochs(); } /// @notice Allows the contract owner to update the address of the /// darknode payment contract. /// @param _darknodePayment The address of the Darknode Payment /// contract. function updateDarknodePayment(IDarknodePayment _darknodePayment) external onlyOwner { require( address(_darknodePayment) != address(0x0), "DarknodeRegistry: invalid Darknode Payment address" ); IDarknodePayment previousDarknodePayment = darknodePayment; darknodePayment = _darknodePayment; emit LogDarknodePaymentUpdated( previousDarknodePayment, darknodePayment ); } /// @notice Allows the contract owner to update the minimum bond. /// @param _nextMinimumBond The minimum bond amount that can be submitted by /// a darknode. function updateMinimumBond(uint256 _nextMinimumBond) external onlyOwner { // Will be updated next epoch nextMinimumBond = _nextMinimumBond; } /// @notice Allows the contract owner to update the minimum pod size. /// @param _nextMinimumPodSize The minimum size of a pod. function updateMinimumPodSize(uint256 _nextMinimumPodSize) external onlyOwner { // Will be updated next epoch nextMinimumPodSize = _nextMinimumPodSize; } /// @notice Allows the contract owner to update the minimum epoch interval. /// @param _nextMinimumEpochInterval The minimum number of blocks between epochs. function updateMinimumEpochInterval(uint256 _nextMinimumEpochInterval) external onlyOwner { // Will be updated next epoch nextMinimumEpochInterval = _nextMinimumEpochInterval; } /// @notice Allow the contract owner to update the DarknodeSlasher contract /// address. /// @param _slasher The new slasher address. function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { require( address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address" ); nextSlasher = _slasher; } /// @notice Allow the DarknodeSlasher contract to slash a portion of darknode's /// bond and deregister it. /// @param _guilty The guilty prover whose bond is being slashed. /// @param _challenger The challenger who should receive a portion of the bond as reward. /// @param _percentage The total percentage of bond to be slashed. function slash( address _guilty, address _challenger, uint256 _percentage ) external onlySlasher onlyDarknode(_guilty) { require(_percentage <= 100, "DarknodeRegistry: invalid percent"); // If the darknode has not been deregistered then deregister it if (isDeregisterable(_guilty)) { deregisterDarknode(_guilty); } uint256 totalBond = store.darknodeBond(_guilty); uint256 penalty = totalBond.div(100).mul(_percentage); uint256 challengerReward = penalty.div(2); uint256 darknodePaymentReward = penalty.sub(challengerReward); if (challengerReward > 0) { // Slash the bond of the failed prover store.updateDarknodeBond(_guilty, totalBond.sub(penalty)); // Distribute the remaining bond into the darknode payment reward pool require( address(darknodePayment) != address(0x0), "DarknodeRegistry: invalid payment address" ); require( ren.transfer( address(darknodePayment.store()), darknodePaymentReward ), "DarknodeRegistry: reward transfer failed" ); require( ren.transfer(_challenger, challengerReward), "DarknodeRegistry: reward transfer failed" ); } emit LogDarknodeSlashed( store.darknodeOperator(_guilty), _guilty, _challenger, _percentage ); } /// @notice Refund the bond of a deregistered darknode. This will make the /// darknode available for registration again. Anyone can call this function /// but the bond will always be refunded to the darknode operator. /// /// @param _darknodeID The darknode ID that will be refunded. function refund(address _darknodeID) external onlyRefundable(_darknodeID) { address darknodeOperator = store.darknodeOperator(_darknodeID); // Remember the bond amount uint256 amount = store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // Refund the operator by transferring REN require( ren.transfer(darknodeOperator, amount), "DarknodeRegistry: bond transfer failed" ); // Emit an event. emit LogDarknodeRefunded(darknodeOperator, _darknodeID, amount); } /// @notice Retrieves the address of the account that registered a darknode. /// @param _darknodeID The ID of the darknode to retrieve the owner for. function getDarknodeOperator(address _darknodeID) external view returns (address payable) { return store.darknodeOperator(_darknodeID); } /// @notice Retrieves the bond amount of a darknode in 10^-18 REN. /// @param _darknodeID The ID of the darknode to retrieve the bond for. function getDarknodeBond(address _darknodeID) external view returns (uint256) { return store.darknodeBond(_darknodeID); } /// @notice Retrieves the encryption public key of the darknode. /// @param _darknodeID The ID of the darknode to retrieve the public key for. function getDarknodePublicKey(address _darknodeID) external view returns (bytes memory) { return store.darknodePublicKey(_darknodeID); } /// @notice Retrieves a list of darknodes which are registered for the /// current epoch. /// @param _start A darknode ID used as an offset for the list. If _start is /// 0x0, the first dark node will be used. _start won't be /// included it is not registered for the epoch. /// @param _count The number of darknodes to retrieve starting from _start. /// If _count is 0, all of the darknodes from _start are /// retrieved. If _count is more than the remaining number of /// registered darknodes, the rest of the list will contain /// 0x0s. function getDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } return getDarknodesFromEpochs(_start, count, false); } /// @notice Retrieves a list of darknodes which were registered for the /// previous epoch. See `getDarknodes` for the parameter documentation. function getPreviousDarknodes(address _start, uint256 _count) external view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodesPreviousEpoch; } return getDarknodesFromEpochs(_start, count, true); } /// @notice Returns whether a darknode is scheduled to become registered /// at next epoch. /// @param _darknodeID The ID of the darknode to return. function isPendingRegistration(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); return registeredAt != 0 && registeredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the pending deregistered state. In /// this state a darknode is still considered registered. function isPendingDeregistration(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt > currentEpoch.blocktime; } /// @notice Returns if a darknode is in the deregistered state. function isDeregistered(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return deregisteredAt != 0 && deregisteredAt <= currentEpoch.blocktime; } /// @notice Returns if a darknode can be deregistered. This is true if the /// darknodes is in the registered state and has not attempted to /// deregister yet. function isDeregisterable(address _darknodeID) public view returns (bool) { uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); // The Darknode is currently in the registered state and has not been // transitioned to the pending deregistration, or deregistered, state return isRegistered(_darknodeID) && deregisteredAt == 0; } /// @notice Returns if a darknode is in the refunded state. This is true /// for darknodes that have never been registered, or darknodes that have /// been deregistered and refunded. function isRefunded(address _darknodeID) public view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); return registeredAt == 0 && deregisteredAt == 0; } /// @notice Returns if a darknode is refundable. This is true for darknodes /// that have been in the deregistered state for one full epoch. function isRefundable(address _darknodeID) public view returns (bool) { return isDeregistered(_darknodeID) && store.darknodeDeregisteredAt(_darknodeID) <= (previousEpoch.blocktime - deregistrationInterval); } /// @notice Returns the registration time of a given darknode. function darknodeRegisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeRegisteredAt(darknodeID); } /// @notice Returns the deregistration time of a given darknode. function darknodeDeregisteredAt(address darknodeID) external view returns (uint256) { return store.darknodeDeregisteredAt(darknodeID); } /// @notice Returns if a darknode is in the registered state. function isRegistered(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, currentEpoch); } /// @notice Returns if a darknode was in the registered state last epoch. function isRegisteredInPreviousEpoch(address _darknodeID) public view returns (bool) { return isRegisteredInEpoch(_darknodeID, previousEpoch); } /// @notice Returns if a darknode was in the registered state for a given /// epoch. /// @param _darknodeID The ID of the darknode. /// @param _epoch One of currentEpoch, previousEpoch. function isRegisteredInEpoch(address _darknodeID, Epoch memory _epoch) private view returns (bool) { uint256 registeredAt = store.darknodeRegisteredAt(_darknodeID); uint256 deregisteredAt = store.darknodeDeregisteredAt(_darknodeID); bool registered = registeredAt != 0 && registeredAt <= _epoch.blocktime; bool notDeregistered = deregisteredAt == 0 || deregisteredAt > _epoch.blocktime; // The Darknode has been registered and has not yet been deregistered, // although it might be pending deregistration return registered && notDeregistered; } /// @notice Returns a list of darknodes registered for either the current /// or the previous epoch. See `getDarknodes` for documentation on the /// parameters `_start` and `_count`. /// @param _usePreviousEpoch If true, use the previous epoch, otherwise use /// the current epoch. function getDarknodesFromEpochs( address _start, uint256 _count, bool _usePreviousEpoch ) private view returns (address[] memory) { uint256 count = _count; if (count == 0) { count = numDarknodes; } address[] memory nodes = new address[](count); // Begin with the first node in the list uint256 n = 0; address next = _start; if (next == address(0)) { next = store.begin(); } // Iterate until all registered Darknodes have been collected while (n < count) { if (next == address(0)) { break; } // Only include Darknodes that are currently registered bool includeNext; if (_usePreviousEpoch) { includeNext = isRegisteredInPreviousEpoch(next); } else { includeNext = isRegistered(next); } if (!includeNext) { next = store.next(next); continue; } nodes[n] = next; next = store.next(next); n += 1; } return nodes; } /// Private function called by `deregister` and `slash` function deregisterDarknode(address _darknodeID) private { address darknodeOperator = store.darknodeOperator(_darknodeID); // Flag the darknode for deregistration store.updateDarknodeDeregisteredAt( _darknodeID, currentEpoch.blocktime.add(minimumEpochInterval) ); numDarknodesNextEpoch = numDarknodesNextEpoch.sub(1); // Emit an event emit LogDarknodeDeregistered(darknodeOperator, _darknodeID); } function getDarknodeCountFromEpochs() private view returns ( uint256, uint256, uint256 ) { // Begin with the first node in the list uint256 nPreviousEpoch = 0; uint256 nCurrentEpoch = 0; uint256 nNextEpoch = 0; address next = store.begin(); // Iterate until all registered Darknodes have been collected while (true) { // End of darknode list. if (next == address(0)) { break; } if (isRegisteredInPreviousEpoch(next)) { nPreviousEpoch += 1; } if (isRegistered(next)) { nCurrentEpoch += 1; } // Darknode is registered and has not deregistered, or is pending // becoming registered. if ( ((isRegistered(next) && !isPendingDeregistration(next)) || isPendingRegistration(next)) ) { nNextEpoch += 1; } next = store.next(next); } return (nPreviousEpoch, nCurrentEpoch, nNextEpoch); } } pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; import "../RenToken/RenToken.sol"; import "./DarknodeRegistryV1ToV2Upgrader.sol"; contract DarknodeRegistryV1ToV2Preupgrader is Ownable { DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryV1ToV2Upgrader public upgrader; address public previousDarknodeRegistryOwner; constructor( DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryV1ToV2Upgrader _upgrader ) public { Ownable.initialize(msg.sender); darknodeRegistryProxy = _darknodeRegistryProxy; upgrader = _upgrader; previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function claimStoreOwnership() public { darknodeRegistryProxy.store().claimOwnership(); } function recover( address[] calldata _darknodeIDs, address _bondRecipient, bytes[] calldata _signatures ) external onlyOwner { forwardDNR(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); darknodeRegistryProxy.transferStoreOwnership( DarknodeRegistryLogicV1(address(this)) ); if (darknodeRegistryProxy.store().owner() != address(this)) { claimStoreOwnership(); } (, uint256 currentEpochBlocktime) = darknodeRegistryProxy .currentEpoch(); uint256 total = 0; for (uint8 i = 0; i < _darknodeIDs.length; i++) { address _darknodeID = _darknodeIDs[i]; // Require darknode to be refundable. { uint256 deregisteredAt = store.darknodeDeregisteredAt( _darknodeID ); bool deregistered = deregisteredAt != 0 && deregisteredAt <= currentEpochBlocktime; require( deregistered, "DarknodeRegistryV1Preupgrader: must be deregistered" ); } address darknodeOperator = store.darknodeOperator(_darknodeID); require( ECDSA.recover( keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n64", "DarknodeRegistry.recover", _darknodeID, _bondRecipient ) ), _signatures[i] ) == darknodeOperator, "DarknodeRegistryV1Preupgrader: invalid signature" ); // Remember the bond amount total += store.darknodeBond(_darknodeID); // Erase the darknode from the registry store.removeDarknode(_darknodeID); // // Refund the operator by transferring REN } require( ren.transfer(_bondRecipient, total), "DarknodeRegistryV1Preupgrader: bond transfer failed" ); store.transferOwnership(address(darknodeRegistryProxy)); darknodeRegistryProxy.claimStoreOwnership(); } function forwardDNR() public onlyOwner { // Claim ownership if (darknodeRegistryProxy.owner() != address(this)) { darknodeRegistryProxy.claimOwnership(); } // Set pending owner to upgrader. if (darknodeRegistryProxy.pendingOwner() != address(upgrader)) { darknodeRegistryProxy.transferOwnership(address(upgrader)); } } function returnDNR() public onlyOwner { darknodeRegistryProxy.transferOwnership(previousDarknodeRegistryOwner); } } pragma solidity ^0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "./DarknodeRegistry.sol"; import "../Governance/RenProxyAdmin.sol"; contract DarknodeRegistryV1ToV2Upgrader is Ownable { RenProxyAdmin public renProxyAdmin; DarknodeRegistryLogicV1 public darknodeRegistryProxy; DarknodeRegistryLogicV2 public darknodeRegistryLogicV2; address public previousAdminOwner; address public previousDarknodeRegistryOwner; constructor( RenProxyAdmin _renProxyAdmin, DarknodeRegistryLogicV1 _darknodeRegistryProxy, DarknodeRegistryLogicV2 _darknodeRegistryLogicV2 ) public { Ownable.initialize(msg.sender); renProxyAdmin = _renProxyAdmin; darknodeRegistryProxy = _darknodeRegistryProxy; darknodeRegistryLogicV2 = _darknodeRegistryLogicV2; previousAdminOwner = renProxyAdmin.owner(); previousDarknodeRegistryOwner = darknodeRegistryProxy.owner(); } function upgrade() public onlyOwner { // Pre-checks uint256 numDarknodes = darknodeRegistryProxy.numDarknodes(); uint256 numDarknodesNextEpoch = darknodeRegistryProxy .numDarknodesNextEpoch(); uint256 numDarknodesPreviousEpoch = darknodeRegistryProxy .numDarknodesPreviousEpoch(); uint256 minimumBond = darknodeRegistryProxy.minimumBond(); uint256 minimumPodSize = darknodeRegistryProxy.minimumPodSize(); uint256 minimumEpochInterval = darknodeRegistryProxy .minimumEpochInterval(); uint256 deregistrationInterval = darknodeRegistryProxy .deregistrationInterval(); RenToken ren = darknodeRegistryProxy.ren(); DarknodeRegistryStore store = darknodeRegistryProxy.store(); IDarknodePayment darknodePayment = darknodeRegistryProxy .darknodePayment(); // Claim and update. darknodeRegistryProxy.claimOwnership(); renProxyAdmin.upgrade( AdminUpgradeabilityProxy( // Cast gateway instance to payable address address(uint160(address(darknodeRegistryProxy))) ), address(darknodeRegistryLogicV2) ); // Post-checks require( numDarknodes == darknodeRegistryProxy.numDarknodes(), "Migrator: expected 'numDarknodes' not to change" ); require( numDarknodesNextEpoch == darknodeRegistryProxy.numDarknodesNextEpoch(), "Migrator: expected 'numDarknodesNextEpoch' not to change" ); require( numDarknodesPreviousEpoch == darknodeRegistryProxy.numDarknodesPreviousEpoch(), "Migrator: expected 'numDarknodesPreviousEpoch' not to change" ); require( minimumBond == darknodeRegistryProxy.minimumBond(), "Migrator: expected 'minimumBond' not to change" ); require( minimumPodSize == darknodeRegistryProxy.minimumPodSize(), "Migrator: expected 'minimumPodSize' not to change" ); require( minimumEpochInterval == darknodeRegistryProxy.minimumEpochInterval(), "Migrator: expected 'minimumEpochInterval' not to change" ); require( deregistrationInterval == darknodeRegistryProxy.deregistrationInterval(), "Migrator: expected 'deregistrationInterval' not to change" ); require( ren == darknodeRegistryProxy.ren(), "Migrator: expected 'ren' not to change" ); require( store == darknodeRegistryProxy.store(), "Migrator: expected 'store' not to change" ); require( darknodePayment == darknodeRegistryProxy.darknodePayment(), "Migrator: expected 'darknodePayment' not to change" ); darknodeRegistryProxy.updateSlasher(IDarknodeSlasher(0x0)); } function recover( address _darknodeID, address _bondRecipient, bytes calldata _signature ) external onlyOwner { return DarknodeRegistryLogicV2(address(darknodeRegistryProxy)).recover( _darknodeID, _bondRecipient, _signature ); } function returnDNR() public onlyOwner { darknodeRegistryProxy._directTransferOwnership( previousDarknodeRegistryOwner ); } function returnProxyAdmin() public onlyOwner { renProxyAdmin.transferOwnership(previousAdminOwner); } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Initializable, Ownable { address public pendingOwner; function initialize(address _nextOwner) public initializer { Ownable.initialize(_nextOwner); } modifier onlyPendingOwner() { require( _msgSender() == pendingOwner, "Claimable: caller is not the pending owner" ); _; } function transferOwnership(address newOwner) public onlyOwner { require( newOwner != owner() && newOwner != pendingOwner, "Claimable: invalid new owner" ); pendingOwner = newOwner; } // Allow skipping two-step transfer if the recipient is known to be a valid // owner, for use in smart-contracts only. function _directTransferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function claimOwnership() public onlyPendingOwner { _transferOwnership(pendingOwner); delete pendingOwner; } } pragma solidity 0.5.17; import "@openzeppelin/upgrades/contracts/upgradeability/ProxyAdmin.sol"; /** * @title RenProxyAdmin * @dev Proxies restrict the proxy's owner from calling functions from the * delegate contract logic. The ProxyAdmin contract allows single account to be * the governance address of both the proxy and the delegate contract logic. */ /* solium-disable-next-line no-empty-blocks */ contract RenProxyAdmin is ProxyAdmin { } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Pausable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol"; contract RenToken is Ownable, ERC20Detailed, ERC20Pausable, ERC20Burnable { string private constant _name = "REN"; string private constant _symbol = "REN"; uint8 private constant _decimals = 18; uint256 public constant INITIAL_SUPPLY = 1000000000 * 10**uint256(_decimals); /// @notice The RenToken Constructor. constructor() public { ERC20Pausable.initialize(msg.sender); ERC20Detailed.initialize(_name, _symbol, _decimals); Ownable.initialize(msg.sender); _mint(msg.sender, INITIAL_SUPPLY); } function transferTokens(address beneficiary, uint256 amount) public onlyOwner returns (bool) { // Note: The deployed version has no revert reason /* solium-disable-next-line error-reason */ require(amount > 0); _transfer(msg.sender, beneficiary, amount); emit Transfer(msg.sender, beneficiary, amount); return true; } } pragma solidity 0.5.17; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "../Governance/Claimable.sol"; contract CanReclaimTokens is Claimable { using SafeERC20 for ERC20; mapping(address => bool) private recoverableTokensBlacklist; function initialize(address _nextOwner) public initializer { Claimable.initialize(_nextOwner); } function blacklistRecoverableToken(address _token) public onlyOwner { recoverableTokensBlacklist[_token] = true; } /// @notice Allow the owner of the contract to recover funds accidentally /// sent to the contract. To withdraw ETH, the token should be set to `0x0`. function recoverTokens(address _token) external onlyOwner { require( !recoverableTokensBlacklist[_token], "CanReclaimTokens: token is not recoverable" ); if (_token == address(0x0)) { msg.sender.transfer(address(this).balance); } else { ERC20(_token).safeTransfer( msg.sender, ERC20(_token).balanceOf(address(this)) ); } } } pragma solidity 0.5.17; /** * @notice LinkedList is a library for a circular double linked list. */ library LinkedList { /* * @notice A permanent NULL node (0x0) in the circular double linked list. * NULL.next is the head, and NULL.previous is the tail. */ address public constant NULL = address(0); /** * @notice A node points to the node before it, and the node after it. If * node.previous = NULL, then the node is the head of the list. If * node.next = NULL, then the node is the tail of the list. */ struct Node { bool inList; address previous; address next; } /** * @notice LinkedList uses a mapping from address to nodes. Each address * uniquely identifies a node, and in this way they are used like pointers. */ struct List { mapping(address => Node) list; uint256 length; } /** * @notice Insert a new node before an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert before the target. */ function insertBefore( List storage self, address target, address newNode ) internal { require(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: not in list" ); // It is expected that this value is sometimes NULL. address prev = self.list[target].previous; self.list[newNode].next = target; self.list[newNode].previous = prev; self.list[target].previous = newNode; self.list[prev].next = newNode; self.list[newNode].inList = true; self.length += 1; } /** * @notice Insert a new node after an existing node. * * @param self The list being used. * @param target The existing node in the list. * @param newNode The next node to insert after the target. */ function insertAfter( List storage self, address target, address newNode ) internal { require(newNode != address(0), "LinkedList: invalid address"); require(!isInList(self, newNode), "LinkedList: already in list"); require( isInList(self, target) || target == NULL, "LinkedList: not in list" ); // It is expected that this value is sometimes NULL. address n = self.list[target].next; self.list[newNode].previous = target; self.list[newNode].next = n; self.list[target].next = newNode; self.list[n].previous = newNode; self.list[newNode].inList = true; self.length += 1; } /** * @notice Remove a node from the list, and fix the previous and next * pointers that are pointing to the removed node. Removing anode that is not * in the list will do nothing. * * @param self The list being using. * @param node The node in the list to be removed. */ function remove(List storage self, address node) internal { require(isInList(self, node), "LinkedList: not in list"); address p = self.list[node].previous; address n = self.list[node].next; self.list[p].next = n; self.list[n].previous = p; // Deleting the node should set this value to false, but we set it here for // explicitness. self.list[node].inList = false; delete self.list[node]; self.length -= 1; } /** * @notice Insert a node at the beginning of the list. * * @param self The list being used. * @param node The node to insert at the beginning of the list. */ function prepend(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertBefore(self, begin(self), node); } /** * @notice Insert a node at the end of the list. * * @param self The list being used. * @param node The node to insert at the end of the list. */ function append(List storage self, address node) internal { // isInList(node) is checked in insertBefore insertAfter(self, end(self), node); } function swap( List storage self, address left, address right ) internal { // isInList(left) and isInList(right) are checked in remove address previousRight = self.list[right].previous; remove(self, right); insertAfter(self, left, right); remove(self, left); insertAfter(self, previousRight, left); } function isInList(List storage self, address node) internal view returns (bool) { return self.list[node].inList; } /** * @notice Get the node at the beginning of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the beginning of the double * linked list. */ function begin(List storage self) internal view returns (address) { return self.list[NULL].next; } /** * @notice Get the node at the end of a double linked list. * * @param self The list being used. * * @return A address identifying the node at the end of the double linked * list. */ function end(List storage self) internal view returns (address) { return self.list[NULL].previous; } function next(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].next; } function previous(List storage self, address node) internal view returns (address) { require(isInList(self, node), "LinkedList: not in list"); return self.list[node].previous; } function elements( List storage self, address _start, uint256 _count ) internal view returns (address[] memory) { require(_count > 0, "LinkedList: invalid count"); require( isInList(self, _start) || _start == address(0), "LinkedList: not in list" ); address[] memory elems = new address[](_count); // Begin with the first node in the list uint256 n = 0; address nextItem = _start; if (nextItem == address(0)) { nextItem = begin(self); } while (n < _count) { if (nextItem == address(0)) { break; } elems[n] = nextItem; nextItem = next(self, nextItem); n += 1; } return elems; } }
Allow the contract owner to update the DarknodeSlasher contract address. _slasher The new slasher address.
function updateSlasher(IDarknodeSlasher _slasher) external onlyOwner { require( address(_slasher) != address(0), "DarknodeRegistry: invalid slasher address" ); nextSlasher = _slasher; }
287,345
./full_match/1/0xf23E95FA6fCED1488D9A7F38e3a11Ad0B9B30166/sources/SSN.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Shiba Social Network", "$SSN") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee =4; uint256 _buyLiquidityFee = 4; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 4; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 0; uint256 totalSupply = 1_000_000_000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
8,370,086
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./PoolTokensContainer.sol"; import "./LiquidityPoolV2ConverterCustomFactory.sol"; import "../../LiquidityPoolConverter.sol"; import "../../interfaces/IConverterFactory.sol"; import "../../../utility/interfaces/IPriceOracle.sol"; /** * @dev Liquidity Pool v2 Converter * * The liquidity pool v2 converter is a specialized version of a converter that uses * price oracles to rebalance the reserve weights in such a way that the primary token * balance always strives to match the staked balance. * * This type of liquidity pool always has 2 reserves and the reserve weights are dynamic. */ contract LiquidityPoolV2Converter is LiquidityPoolConverter { uint32 internal constant HIGH_FEE_UPPER_BOUND = 997500; // high fee upper bound in PPM units uint256 internal constant MAX_RATE_FACTOR_LOWER_BOUND = 1e30; struct Fraction { uint256 n; // numerator uint256 d; // denominator } IPriceOracle public priceOracle; // external price oracle IERC20Token public primaryReserveToken; // primary reserve in the pool IERC20Token public secondaryReserveToken; // secondary reserve in the pool (cache) mapping (IERC20Token => uint256) private stakedBalances; // tracks the staked liquidity in the pool plus the fees mapping (IERC20Token => ISmartToken) private reservesToPoolTokens; // maps each reserve to its pool token mapping (ISmartToken => IERC20Token) private poolTokensToReserves; // maps each pool token to its reserve uint8 public amplificationFactor = 20; // factor to use for conversion calculations (reduces slippage) uint256 public externalRatePropagationTime = 1 hours; // the time it takes for the external rate to fully take effect uint256 public prevConversionTime; // previous conversion time in seconds // factors used in fee calculations uint32 public lowFeeFactor = 200000; uint32 public highFeeFactor = 800000; // used by the temp liquidity limit mechanism during the beta mapping (IERC20Token => uint256) public maxStakedBalances; bool public maxStakedBalanceEnabled = true; /** * @dev triggered when the amplification factor is updated * * @param _prevAmplificationFactor previous amplification factor * @param _newAmplificationFactor new amplification factor */ event AmplificationFactorUpdate(uint8 _prevAmplificationFactor, uint8 _newAmplificationFactor); /** * @dev triggered when the external rate propagation time is updated * * @param _prevPropagationTime previous external rate propagation time, in seconds * @param _newPropagationTime new external rate propagation time, in seconds */ event ExternalRatePropagationTimeUpdate(uint256 _prevPropagationTime, uint256 _newPropagationTime); /** * @dev triggered when the fee factors are updated * * @param _prevLowFactor previous low factor percentage, represented in ppm * @param _newLowFactor new low factor percentage, represented in ppm * @param _prevHighFactor previous high factor percentage, represented in ppm * @param _newHighFactor new high factor percentage, represented in ppm */ event FeeFactorsUpdate(uint256 _prevLowFactor, uint256 _newLowFactor, uint256 _prevHighFactor, uint256 _newHighFactor); /** * @dev initializes a new LiquidityPoolV2Converter instance * * @param _poolTokensContainer pool tokens container governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm */ constructor(IPoolTokensContainer _poolTokensContainer, IContractRegistry _registry, uint32 _maxConversionFee) public LiquidityPoolConverter(_poolTokensContainer, _registry, _maxConversionFee) { } // ensures the address is a pool token modifier validPoolToken(ISmartToken _address) { _validPoolToken(_address); _; } // error message binary size optimization function _validPoolToken(ISmartToken _address) internal view { require(address(poolTokensToReserves[_address]) != address(0), "ERR_INVALID_POOL_TOKEN"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public override pure returns (uint16) { return 2; } /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public override view returns (bool) { return super.isActive() && address(priceOracle) != address(0); } /** * @dev sets the pool's primary reserve token / price oracles and activates the pool * each oracle must be able to provide the rate for each reserve token * note that the oracle must be whitelisted prior to the call * can only be called by the owner while the pool is inactive * * @param _primaryReserveToken address of the pool's primary reserve token * @param _primaryReserveOracle address of a chainlink price oracle for the primary reserve token * @param _secondaryReserveOracle address of a chainlink price oracle for the secondary reserve token */ function activate( IERC20Token _primaryReserveToken, IChainlinkPriceOracle _primaryReserveOracle, IChainlinkPriceOracle _secondaryReserveOracle) public inactive ownerOnly validReserve(_primaryReserveToken) notThis(address(_primaryReserveOracle)) notThis(address(_secondaryReserveOracle)) validAddress(address(_primaryReserveOracle)) validAddress(address(_secondaryReserveOracle)) { // validate anchor ownership require(anchor.owner() == address(this), "ERR_ANCHOR_NOT_OWNED"); // validate oracles IWhitelist oracleWhitelist = IWhitelist(addressOf(CHAINLINK_ORACLE_WHITELIST)); require(oracleWhitelist.isWhitelisted(address(_primaryReserveOracle)) && oracleWhitelist.isWhitelisted(address(_secondaryReserveOracle)), "ERR_INVALID_ORACLE"); // create the converter's pool tokens if they don't already exist createPoolTokens(); // sets the primary & secondary reserve tokens primaryReserveToken = _primaryReserveToken; if (_primaryReserveToken == reserveTokens[0]) secondaryReserveToken = reserveTokens[1]; else secondaryReserveToken = reserveTokens[0]; // creates and initalizes the price oracle and sets initial rates LiquidityPoolV2ConverterCustomFactory customFactory = LiquidityPoolV2ConverterCustomFactory(address(IConverterFactory(addressOf(CONVERTER_FACTORY)).customFactories(converterType()))); priceOracle = customFactory.createPriceOracle( _primaryReserveToken, secondaryReserveToken, _primaryReserveOracle, _secondaryReserveOracle); // if we are upgrading from an older converter, make sure that reserve balances are in-sync and rebalance uint256 primaryReserveStakedBalance = reserveStakedBalance(primaryReserveToken); uint256 primaryReserveBalance = reserveBalance(primaryReserveToken); uint256 secondaryReserveBalance = reserveBalance(secondaryReserveToken); if (primaryReserveStakedBalance == primaryReserveBalance) { if (primaryReserveStakedBalance > 0 || secondaryReserveBalance > 0) { rebalance(); } } else if (primaryReserveStakedBalance > 0 && primaryReserveBalance > 0 && secondaryReserveBalance > 0) { rebalance(); } emit Activation(converterType(), anchor, true); } /** * @dev returns the staked balance of a given reserve token * * @param _reserveToken reserve token address * * @return staked balance */ function reserveStakedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return stakedBalances[_reserveToken]; } /** * @dev returns the amplified balance of a given reserve token * * @param _reserveToken reserve token address * * @return amplified balance */ function reserveAmplifiedBalance(IERC20Token _reserveToken) public view validReserve(_reserveToken) returns (uint256) { return amplifiedBalance(_reserveToken); } /** * @dev sets the reserve's staked balance * can only be called by the upgrader contract while the upgrader is the owner * * @param _reserveToken reserve token address * @param _balance new reserve staked balance */ function setReserveStakedBalance(IERC20Token _reserveToken, uint256 _balance) public ownerOnly only(CONVERTER_UPGRADER) validReserve(_reserveToken) { stakedBalances[_reserveToken] = _balance; } /** * @dev sets the max staked balance for both reserves * available as a temporary mechanism during the beta * can only be called by the owner * * @param _reserve1MaxStakedBalance max staked balance for reserve 1 * @param _reserve2MaxStakedBalance max staked balance for reserve 2 */ function setMaxStakedBalances(uint256 _reserve1MaxStakedBalance, uint256 _reserve2MaxStakedBalance) public ownerOnly { maxStakedBalances[reserveTokens[0]] = _reserve1MaxStakedBalance; maxStakedBalances[reserveTokens[1]] = _reserve2MaxStakedBalance; } /** * @dev disables the max staked balance mechanism * available as a temporary mechanism during the beta * once disabled, it cannot be re-enabled * can only be called by the owner */ function disableMaxStakedBalances() public ownerOnly { maxStakedBalanceEnabled = false; } /** * @dev returns the pool token address by the reserve token address * * @param _reserveToken reserve token address * * @return pool token address */ function poolToken(IERC20Token _reserveToken) public view returns (ISmartToken) { return reservesToPoolTokens[_reserveToken]; } /** * @dev returns the maximum number of pool tokens that can currently be liquidated * * @param _poolToken address of the pool token * * @return liquidation limit */ function liquidationLimit(ISmartToken _poolToken) public view returns (uint256) { // get the pool token supply uint256 poolTokenSupply = _poolToken.totalSupply(); // get the reserve token associated with the pool token and its balance / staked balance IERC20Token reserveToken = poolTokensToReserves[_poolToken]; uint256 balance = reserveBalance(reserveToken); uint256 stakedBalance = stakedBalances[reserveToken]; // calculate the amount that's available for liquidation return balance.mul(poolTokenSupply).div(stakedBalance); } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive and * 2 reserves aren't defined yet * * @param _token address of the reserve token * @param _weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IERC20Token _token, uint32 _weight) public override ownerOnly { // verify that the converter doesn't have 2 reserves yet require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); super.addReserve(_token, _weight); } /** * @dev returns the effective rate of 1 primary token in secondary tokens * * @return rate of 1 primary token in secondary tokens (numerator) * @return rate of 1 primary token in secondary tokens (denominator) */ function effectiveTokensRate() public view returns (uint256, uint256) { Fraction memory rate = rateFromPrimaryWeight(effectivePrimaryWeight()); return (rate.n, rate.d); } /** * @dev returns the effective reserve tokens weights * * @return reserve1 weight * @return reserve2 weight */ function effectiveReserveWeights() public view returns (uint256, uint256) { uint32 primaryReserveWeight = effectivePrimaryWeight(); if (primaryReserveToken == reserveTokens[0]) { return (primaryReserveWeight, inverseWeight(primaryReserveWeight)); } return (inverseWeight(primaryReserveWeight), primaryReserveWeight); } /** * @dev updates the amplification factor * can only be called by the contract owner * * @param _amplificationFactor new amplification factor */ function setAmplificationFactor(uint8 _amplificationFactor) public ownerOnly { emit AmplificationFactorUpdate(amplificationFactor, _amplificationFactor); amplificationFactor = _amplificationFactor; } /** * @dev updates the external rate propagation time * can only be called by the contract owner * * @param _propagationTime new rate propagation time, in seconds */ function setExternalRatePropagationTime(uint256 _propagationTime) public ownerOnly { emit ExternalRatePropagationTimeUpdate(externalRatePropagationTime, _propagationTime); externalRatePropagationTime = _propagationTime; } /** * @dev updates the fee factors * can only be called by the contract owner * * @param _lowFactor new low fee factor, represented in ppm * @param _highFactor new high fee factor, represented in ppm */ function setFeeFactors(uint32 _lowFactor, uint32 _highFactor) public ownerOnly { require(_lowFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); require(_highFactor <= PPM_RESOLUTION, "ERR_INVALID_FEE_FACTOR"); emit FeeFactorsUpdate(lowFeeFactor, _lowFactor, highFeeFactor, _highFactor); lowFeeFactor = _lowFactor; highFeeFactor = _highFactor; } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) public override view active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256, uint256) { // validate input require(_sourceToken != _targetToken, "ERR_SAME_SOURCE_TARGET"); // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // get the source token effective / external weights (uint32 sourceTokenWeight, uint32 externalSourceTokenWeight) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); if (_targetToken == primaryReserveToken) { sourceTokenWeight = inverseWeight(sourceTokenWeight); externalSourceTokenWeight = inverseWeight(externalSourceTokenWeight); } // return the target amount and the fee using the updated reserve weights return targetAmountAndFee( _sourceToken, _targetToken, sourceTokenWeight, inverseWeight(sourceTokenWeight), externalRate, inverseWeight(externalSourceTokenWeight), _amount); } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _trader address of the caller who executed the conversion * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, address _trader, address payable _beneficiary) internal override active validReserve(_sourceToken) validReserve(_targetToken) returns (uint256) { // convert and get the target amount and fee (uint256 amount, uint256 fee) = doConvert(_sourceToken, _targetToken, _amount); // update the previous conversion time prevConversionTime = time(); // transfer funds to the beneficiary in the to reserve token if (_targetToken == ETH_RESERVE_ADDRESS) { _beneficiary.transfer(amount); } else { safeTransfer(_targetToken, _beneficiary, amount); } // dispatch the conversion event dispatchConversionEvent(_sourceToken, _targetToken, _trader, _amount, amount, fee); // dispatch rate updates for the pool / reserve tokens dispatchRateEvents(_sourceToken, _targetToken, reserves[_sourceToken].weight, reserves[_targetToken].weight); // return the conversion result amount return amount; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * * @return amount of target tokens received * @return fee amount */ function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); // pre-conversion preparation - update the weights if needed and get the target amount and feee (uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance uint256 targetReserveBalance = reserves[_targetToken].balance; require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // ensure that the input amount was already deposited if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT"); // sync the reserve balances syncReserveBalance(_sourceToken); reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount); // if the pool is in deficit, add half the fee to the target staked balance, otherwise add all stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2); // return a tuple of [target amount (excluding fee), fee] return (targetAmount, fee); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param _reserveToken address of the reserve token to add liquidity to * @param _amount amount of liquidity to add * @param _minReturn minimum return-amount of pool tokens * * @return amount of pool tokens minted */ function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn) public payable protected active validReserve(_reserveToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // verify that msg.value is identical to the provided amount for ETH reserve, or 0 otherwise require(_reserveToken == ETH_RESERVE_ADDRESS ? msg.value == _amount : msg.value == 0, "ERR_ETH_AMOUNT_MISMATCH"); // sync the reserve balances just in case syncReserveBalances(); // for ETH reserve, deduct the amount that was just synced (since it's already in the converter) if (_reserveToken == ETH_RESERVE_ADDRESS) { reserves[ETH_RESERVE_ADDRESS].balance = reserves[ETH_RESERVE_ADDRESS].balance.sub(msg.value); } // get the reserve staked balance before adding the liquidity to it uint256 initialStakedBalance = stakedBalances[_reserveToken]; // during the beta, ensure that the new staked balance isn't greater than the max limit if (maxStakedBalanceEnabled) { require(maxStakedBalances[_reserveToken] == 0 || initialStakedBalance.add(_amount) <= maxStakedBalances[_reserveToken], "ERR_MAX_STAKED_BALANCE_REACHED"); } // get the pool token associated with the reserve and its supply ISmartToken reservePoolToken = reservesToPoolTokens[_reserveToken]; uint256 poolTokenSupply = reservePoolToken.totalSupply(); // for non ETH reserve, transfer the funds from the user to the pool if (_reserveToken != ETH_RESERVE_ADDRESS) safeTransferFrom(_reserveToken, msg.sender, address(this), _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[_reserveToken].balance = reserves[_reserveToken].balance.add(_amount); stakedBalances[_reserveToken] = initialStakedBalance.add(_amount); // calculate how many pool tokens to mint // for an empty pool, the price is 1:1, otherwise the price is based on the ratio // between the pool token supply and the staked balance uint256 poolTokenAmount = 0; if (initialStakedBalance == 0 || poolTokenSupply == 0) poolTokenAmount = _amount; else poolTokenAmount = _amount.mul(poolTokenSupply).div(initialStakedBalance); require(poolTokenAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // mint new pool tokens to the caller IPoolTokensContainer(address(anchor)).mint(reservePoolToken, msg.sender, poolTokenAmount); // rebalance the pool's reserve weights rebalance(rate); // dispatch the LiquidityAdded event emit LiquidityAdded(msg.sender, _reserveToken, _amount, initialStakedBalance.add(_amount), poolTokenSupply.add(poolTokenAmount)); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(reservePoolToken, poolTokenSupply.add(poolTokenAmount), _reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of pool tokens minted return poolTokenAmount; } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param _poolToken address of the pool token * @param _amount amount of pool tokens to burn * @param _minReturn minimum return-amount of reserve tokens * * @return amount of liquidity removed */ function removeLiquidity(ISmartToken _poolToken, uint256 _amount, uint256 _minReturn) public protected active validPoolToken(_poolToken) greaterThanZero(_amount) greaterThanZero(_minReturn) returns (uint256) { // sync the reserve balances just in case syncReserveBalances(); // get the pool token supply before burning the caller's shares uint256 initialPoolSupply = _poolToken.totalSupply(); // get the reserve token return before burning the caller's shares (uint256 reserveAmount, ) = removeLiquidityReturnAndFee(_poolToken, _amount); require(reserveAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); // get the reserve token associated with the pool token IERC20Token reserveToken = poolTokensToReserves[_poolToken]; // burn the caller's pool tokens IPoolTokensContainer(address(anchor)).burn(_poolToken, msg.sender, _amount); // get the rate before updating the staked balance Fraction memory rate = rebalanceRate(); // sync the reserve balance / staked balance reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount); uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount); stakedBalances[reserveToken] = newStakedBalance; // transfer the reserve amount to the caller if (reserveToken == ETH_RESERVE_ADDRESS) msg.sender.transfer(reserveAmount); else safeTransfer(reserveToken, msg.sender, reserveAmount); // rebalance the pool's reserve weights rebalance(rate); uint256 newPoolTokenSupply = initialPoolSupply.sub(_amount); // dispatch the LiquidityRemoved event emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newStakedBalance, newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token dispatchPoolTokenRateUpdateEvent(_poolToken, newPoolTokenSupply, reserveToken); // dispatch the `TokenRateUpdate` event for the reserve tokens dispatchTokenRateUpdateEvent(reserveTokens[0], reserveTokens[1], 0, 0); // return the amount of liquidity removed return reserveAmount; } /** * @dev calculates the amount of reserve tokens entitled for a given amount of pool tokens * note that a fee is applied according to the equilibrium level of the primary reserve token * * @param _poolToken address of the pool token * @param _amount amount of pool tokens * * @return amount after fee and fee, in reserve token units */ function removeLiquidityReturnAndFee(ISmartToken _poolToken, uint256 _amount) public view returns (uint256, uint256) { uint256 totalSupply = _poolToken.totalSupply(); uint256 stakedBalance = stakedBalances[poolTokensToReserves[_poolToken]]; if (_amount < totalSupply) { (uint256 min, uint256 max) = tokensRateAccuracy(); uint256 amountBeforeFee = _amount.mul(stakedBalance).div(totalSupply); uint256 amountAfterFee = amountBeforeFee.mul(min).div(max); return (amountAfterFee, amountBeforeFee - amountAfterFee); } return (stakedBalance, 0); } /** * @dev calculates the tokens-rate accuracy * * @return the tokens-rate accuracy as a tuple of numerator and denominator */ function tokensRateAccuracy() internal view returns (uint256, uint256) { uint32 weight = reserves[primaryReserveToken].weight; Fraction memory poolRate = tokensRate(primaryReserveToken, secondaryReserveToken, weight, inverseWeight(weight)); (uint256 n, uint256 d) = effectiveTokensRate(); (uint256 x, uint256 y) = reducedRatio(poolRate.n.mul(d), poolRate.d.mul(n), MAX_RATE_FACTOR_LOWER_BOUND); return x < y ? (x, y) : (y, x); } /** * @dev returns the expected target amount of converting one reserve to another along with the fee * this version of the function expects the reserve weights as an input (gas optimization) * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _amount amount of tokens received from the user * * @return expected target amount * @return expected fee */ function targetAmountAndFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _amount) private view returns (uint256, uint256) { // get the tokens amplified balances uint256 sourceBalance = amplifiedBalance(_sourceToken); uint256 targetBalance = amplifiedBalance(_targetToken); // get the target amount uint256 targetAmount = IBancorFormula(addressOf(BANCOR_FORMULA)).crossReserveTargetAmount( sourceBalance, _sourceWeight, targetBalance, _targetWeight, _amount ); // if the target amount is larger than the target reserve balance, return 0 // this can happen due to the amplification require(targetAmount <= reserves[_targetToken].balance, "ERR_TARGET_AMOUNT_TOO_HIGH"); // return a tuple of [target amount (excluding fee), fee] uint256 fee = calculateFee(_sourceToken, _targetToken, _sourceWeight, _targetWeight, _externalRate, _targetExternalWeight, targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the fee amount for a given target amount * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight * @param _externalRate external rate of 1 primary token in secondary tokens * @param _targetExternalWeight target reserve token weight based on external rate * @param _targetAmount target amount * * @return fee amount */ function calculateFee( IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight, Fraction memory _externalRate, uint32 _targetExternalWeight, uint256 _targetAmount) internal view returns (uint256) { // get the external rate of 1 source token in target tokens Fraction memory targetExternalRate; if (_targetToken == primaryReserveToken) { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.n, _externalRate.d); } else { (targetExternalRate.n, targetExternalRate.d) = (_externalRate.d, _externalRate.n); } // get the token pool rate Fraction memory currentRate = tokensRate(_targetToken, _sourceToken, _targetWeight, _sourceWeight); if (compareRates(currentRate, targetExternalRate) < 0) { uint256 lo = currentRate.n.mul(targetExternalRate.d); uint256 hi = targetExternalRate.n.mul(currentRate.d); (lo, hi) = reducedRatio(hi - lo, hi, MAX_RATE_FACTOR_LOWER_BOUND); // apply the high fee only if the ratio between the effective weight and the external (target) weight is below the high fee upper bound uint32 feeFactor; if (uint256(_targetWeight).mul(PPM_RESOLUTION) < uint256(_targetExternalWeight).mul(HIGH_FEE_UPPER_BOUND)) { feeFactor = highFeeFactor; } else { feeFactor = lowFeeFactor; } return _targetAmount.mul(lo).mul(feeFactor).div(hi.mul(PPM_RESOLUTION)); } return 0; } /** * @dev calculates the deficit in the pool (in secondary reserve token amount) * * @param _externalRate external rate of 1 primary token in secondary tokens * * @return the deficit in the pool */ function calculateDeficit(Fraction memory _externalRate) internal view returns (uint256) { IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization IERC20Token secondaryReserveTokenLocal = secondaryReserveToken; // gas optimization // get the amount of primary balances in secondary tokens using the external rate uint256 primaryBalanceInSecondary = reserves[primaryReserveTokenLocal].balance.mul(_externalRate.n).div(_externalRate.d); uint256 primaryStakedInSecondary = stakedBalances[primaryReserveTokenLocal].mul(_externalRate.n).div(_externalRate.d); // if the total balance is lower than the total staked balance, return the delta uint256 totalBalance = primaryBalanceInSecondary.add(reserves[secondaryReserveTokenLocal].balance); uint256 totalStaked = primaryStakedInSecondary.add(stakedBalances[secondaryReserveTokenLocal]); if (totalBalance < totalStaked) { return totalStaked - totalBalance; } return 0; } /** * @dev updates the weights based on the effective weights calculation if needed * and returns the target amount and fee * * @param _sourceToken source ERC20 token * @param _targetToken target ERC20 token * @param _amount amount of tokens to convert (in units of the source token) * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return expected target amount * @return expected fee */ function prepareConversion( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal returns (uint256, uint256) { // get the source token effective / external weights (uint32 effectiveSourceReserveWeight, uint32 externalSourceReserveWeight) = effectiveAndExternalPrimaryWeight(_externalRate, _externalRateUpdateTime); if (_targetToken == primaryReserveToken) { effectiveSourceReserveWeight = inverseWeight(effectiveSourceReserveWeight); externalSourceReserveWeight = inverseWeight(externalSourceReserveWeight); } // check if the weights need to be updated if (reserves[_sourceToken].weight != effectiveSourceReserveWeight) { // update the weights reserves[_sourceToken].weight = effectiveSourceReserveWeight; reserves[_targetToken].weight = inverseWeight(effectiveSourceReserveWeight); } // get expected target amount and fee return targetAmountAndFee( _sourceToken, _targetToken, effectiveSourceReserveWeight, inverseWeight(effectiveSourceReserveWeight), _externalRate, inverseWeight(externalSourceReserveWeight), _amount); } /** * @dev creates the converter's pool tokens * note that technically pool tokens can be created on deployment but gas limit * might get too high for a block, so creating them on first activation * */ function createPoolTokens() internal { IPoolTokensContainer container = IPoolTokensContainer(address(anchor)); ISmartToken[] memory poolTokens = container.poolTokens(); bool initialSetup = poolTokens.length == 0; uint256 reserveCount = reserveTokens.length; for (uint256 i = 0; i < reserveCount; i++) { ISmartToken reservePoolToken; if (initialSetup) { reservePoolToken = container.createToken(); } else { reservePoolToken = poolTokens[i]; } // cache the pool token address (gas optimization) reservesToPoolTokens[reserveTokens[i]] = reservePoolToken; poolTokensToReserves[reservePoolToken] = reserveTokens[i]; } } /** * @dev returns the effective primary reserve token weight * * @return effective primary reserve weight */ function effectivePrimaryWeight() internal view returns (uint32) { // get the external rate between the reserves along with its update time Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); (uint32 effectiveWeight,) = effectiveAndExternalPrimaryWeight(externalRate, externalRateUpdateTime); return effectiveWeight; } /** * @dev returns the effective and the external primary reserve token weights * * @param _externalRate external rate of 1 primary token in secondary tokens * @param _externalRateUpdateTime external rate update time * * @return effective primary reserve weight * @return external primary reserve weight */ function effectiveAndExternalPrimaryWeight(Fraction memory _externalRate, uint256 _externalRateUpdateTime) internal view returns (uint32, uint32) { // get the external rate primary reserve weight uint32 externalPrimaryReserveWeight = primaryWeightFromRate(_externalRate); // get the primary reserve weight IERC20Token primaryReserveTokenLocal = primaryReserveToken; // gas optimization uint32 primaryReserveWeight = reserves[primaryReserveTokenLocal].weight; // if the weights are already at their target, return current weights if (primaryReserveWeight == externalPrimaryReserveWeight) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // get the elapsed time since the last conversion time and the external rate update time uint256 referenceTime = prevConversionTime; if (referenceTime < _externalRateUpdateTime) { referenceTime = _externalRateUpdateTime; } // limit the reference time by current time uint256 currentTime = time(); if (referenceTime > currentTime) { referenceTime = currentTime; } // if no time has passed since the reference time, return current weights (also ensures a single update per block) uint256 elapsedTime = currentTime - referenceTime; if (elapsedTime == 0) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // find the token whose weight is lower than the target weight and get its pool rate - if it's // lower than external rate, update the weights Fraction memory poolRate = tokensRate( primaryReserveTokenLocal, secondaryReserveToken, primaryReserveWeight, inverseWeight(primaryReserveWeight)); bool updateWeights = false; if (primaryReserveWeight < externalPrimaryReserveWeight) { updateWeights = compareRates(poolRate, _externalRate) < 0; } else { updateWeights = compareRates(poolRate, _externalRate) > 0; } if (!updateWeights) { return (primaryReserveWeight, externalPrimaryReserveWeight); } // if the elapsed time since the reference rate is equal or larger than the propagation time, // the external rate should take full effect if (elapsedTime >= externalRatePropagationTime) { return (externalPrimaryReserveWeight, externalPrimaryReserveWeight); } // move the weights towards their target by the same proportion of elapsed time out of the rate propagation time primaryReserveWeight = uint32(weightedAverageIntegers( primaryReserveWeight, externalPrimaryReserveWeight, elapsedTime, externalRatePropagationTime)); return (primaryReserveWeight, externalPrimaryReserveWeight); } /** * @dev returns the current rate for add/remove liquidity rebalancing * only used to circumvent the `stack too deep` compiler error * * @return effective rate */ function rebalanceRate() private view returns (Fraction memory) { // if one of the balances is 0, return the external rate if (reserves[primaryReserveToken].balance == 0 || reserves[secondaryReserveToken].balance == 0) { Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); return externalRate; } // return the rate based on the current rate return tokensRate(primaryReserveToken, secondaryReserveToken, 0, 0); } /** * @dev updates the reserve weights based on the external rate */ function rebalance() private { // get the external rate Fraction memory externalRate; (externalRate.n, externalRate.d) = priceOracle.latestRate(primaryReserveToken, secondaryReserveToken); // rebalance the weights based on the external rate rebalance(externalRate); } /** * @dev updates the reserve weights based on the given rate * * @param _rate rate of 1 primary token in secondary tokens */ function rebalance(Fraction memory _rate) private { // get the new primary reserve weight uint256 a = amplifiedBalance(primaryReserveToken).mul(_rate.n); uint256 b = amplifiedBalance(secondaryReserveToken).mul(_rate.d); (uint256 x, uint256 y) = normalizedRatio(a, b, PPM_RESOLUTION); // update the reserve weights with the new values reserves[primaryReserveToken].weight = uint32(x); reserves[secondaryReserveToken].weight = uint32(y); } /** * @dev returns the amplified balance of a given reserve token * this version skips the input validation (gas optimization) * * @param _reserveToken reserve token address * * @return amplified balance */ function amplifiedBalance(IERC20Token _reserveToken) internal view returns (uint256) { return stakedBalances[_reserveToken].mul(amplificationFactor - 1).add(reserves[_reserveToken].balance); } /** * @dev returns the effective primary reserve weight based on the staked balance, current balance and given rate * * @param _rate rate of 1 primary token in secondary tokens * * @return primary reserve weight */ function primaryWeightFromRate(Fraction memory _rate) private view returns (uint32) { uint256 a = stakedBalances[primaryReserveToken].mul(_rate.n); uint256 b = stakedBalances[secondaryReserveToken].mul(_rate.d); (uint256 x,) = normalizedRatio(a, b, PPM_RESOLUTION); return uint32(x); } /** * @dev returns the effective rate based on the staked balance, current balance and given primary reserve weight * * @param _primaryReserveWeight primary reserve weight * * @return effective rate of 1 primary token in secondary tokens */ function rateFromPrimaryWeight(uint32 _primaryReserveWeight) private view returns (Fraction memory) { uint256 n = stakedBalances[secondaryReserveToken].mul(_primaryReserveWeight); uint256 d = stakedBalances[primaryReserveToken].mul(inverseWeight(_primaryReserveWeight)); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev calculates and returns the rate between two reserve tokens * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 * * @return rate */ function tokensRate(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private view returns (Fraction memory) { if (_token1Weight == 0) { _token1Weight = reserves[_token1].weight; } if (_token2Weight == 0) { _token2Weight = inverseWeight(_token1Weight); } uint256 n = amplifiedBalance(_token2).mul(_token1Weight); uint256 d = amplifiedBalance(_token1).mul(_token2Weight); (n, d) = reducedRatio(n, d, MAX_RATE_FACTOR_LOWER_BOUND); return Fraction(n, d); } /** * @dev dispatches rate events for both reserve tokens and for the target pool token * only used to circumvent the `stack too deep` compiler error * * @param _sourceToken contract address of the source reserve token * @param _targetToken contract address of the target reserve token * @param _sourceWeight source reserve token weight * @param _targetWeight target reserve token weight */ function dispatchRateEvents(IERC20Token _sourceToken, IERC20Token _targetToken, uint32 _sourceWeight, uint32 _targetWeight) private { dispatchTokenRateUpdateEvent(_sourceToken, _targetToken, _sourceWeight, _targetWeight); // dispatch the `TokenRateUpdate` event for the pool token // the target reserve pool token rate is the only one that's affected // by conversions since conversion fees are applied to the target reserve ISmartToken targetPoolToken = poolToken(_targetToken); uint256 targetPoolTokenSupply = targetPoolToken.totalSupply(); dispatchPoolTokenRateUpdateEvent(targetPoolToken, targetPoolTokenSupply, _targetToken); } /** * @dev dispatches token rate update event * only used to circumvent the `stack too deep` compiler error * * @param _token1 contract address of the token to calculate the rate of one unit of * @param _token2 contract address of the token to calculate the rate of one `_token1` unit in * @param _token1Weight reserve weight of token1 * @param _token2Weight reserve weight of token2 */ function dispatchTokenRateUpdateEvent(IERC20Token _token1, IERC20Token _token2, uint32 _token1Weight, uint32 _token2Weight) private { // dispatch token rate update event Fraction memory rate = tokensRate(_token1, _token2, _token1Weight, _token2Weight); emit TokenRateUpdate(_token1, _token2, rate.n, rate.d); } /** * @dev dispatches the `TokenRateUpdate` for the pool token * only used to circumvent the `stack too deep` compiler error * * @param _poolToken address of the pool token * @param _poolTokenSupply total pool token supply * @param _reserveToken address of the reserve token */ function dispatchPoolTokenRateUpdateEvent(ISmartToken _poolToken, uint256 _poolTokenSupply, IERC20Token _reserveToken) private { emit TokenRateUpdate(_poolToken, _reserveToken, stakedBalances[_reserveToken], _poolTokenSupply); } // utilities /** * @dev returns the inverse weight for a given weight * * @param _weight reserve token weight * * @return reserve weight */ function inverseWeight(uint32 _weight) internal pure returns (uint32) { return PPM_RESOLUTION - _weight; } /** * @dev returns the current time */ function time() internal virtual view returns (uint256) { return now; } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)". */ function normalizedRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { if (_a == _b) return (_scale / 2, _scale / 2); if (_a < _b) return accurateRatio(_a, _b, _scale); (uint256 y, uint256 x) = accurateRatio(_b, _a, _scale); return (x, y); } /** * @dev computes "scale * a / (a + b)" and "scale * b / (a + b)", assuming that "a < b". */ function accurateRatio(uint256 _a, uint256 _b, uint256 _scale) internal pure returns (uint256, uint256) { uint256 maxVal = uint256(-1) / _scale; if (_a > maxVal) { uint256 c = _a / (maxVal + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * _scale, _a.add(_b)); uint256 y = _scale - x; return (x, y); } /** * @dev computes a reduced-scalar ratio * * @param _n ratio numerator * @param _d ratio denominator * @param _max maximum desired scalar * * @return ratio's numerator and denominator */ function reducedRatio(uint256 _n, uint256 _d, uint256 _max) internal pure returns (uint256, uint256) { if (_n > _max || _d > _max) return normalizedRatio(_n, _d, _max); return (_n, _d); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + _n % _d / (_d - _d / 2); } /** * @dev calculates the weighted-average of two integers * * @param _x first integer * @param _y second integer * @param _n factor numerator * @param _d factor denominator * * @return the weighted-average of the given integers */ function weightedAverageIntegers(uint256 _x, uint256 _y, uint256 _n, uint256 _d) internal pure returns (uint256) { return _x.mul(_d).add(_y.mul(_n)).sub(_x.mul(_n)).div(_d); } /** * @dev compares two rates * * @param _rate1 first rate to compare * @param _rate2 second rate to compare * * @return `-1` if `_rate1` is lower than `_rate2`, `1` if `_rate1` is higher than `_rate2`, 0 if the rates are identical */ function compareRates(Fraction memory _rate1, Fraction memory _rate2) internal pure returns (int8) { uint256 x = _rate1.n.mul(_rate2.d); uint256 y = _rate2.n.mul(_rate1.d); if (x < y) return -1; if (x > y) return 1; return 0; } }
converts a specific amount of source tokens to target tokens can only be called by the bancor network contract _sourceToken source ERC20 token _targetToken target ERC20 token _amount amount of tokens to convert (in units of the source token) return amount of target tokens received return fee amount/ get the external rate between the reserves along with its update time pre-conversion preparation - update the weights if needed and get the target amount and feee ensure that the trade gives something in return ensure that the trade won't deplete the reserve balance ensure that the input amount was already deposited sync the reserve balances if the pool is in deficit, add half the fee to the target staked balance, otherwise add all return a tuple of [target amount (excluding fee), fee]
function doConvert(IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount) private returns (uint256, uint256) { Fraction memory externalRate; uint256 externalRateUpdateTime; (externalRate.n, externalRate.d, externalRateUpdateTime) = priceOracle.latestRateAndUpdateTime(primaryReserveToken, secondaryReserveToken); (uint256 targetAmount, uint256 fee) = prepareConversion(_sourceToken, _targetToken, _amount, externalRate, externalRateUpdateTime); require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); uint256 targetReserveBalance = reserves[_targetToken].balance; require(targetAmount < targetReserveBalance, "ERR_TARGET_AMOUNT_TOO_HIGH"); if (_sourceToken == ETH_RESERVE_ADDRESS) require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); else require(msg.value == 0 && _sourceToken.balanceOf(address(this)).sub(reserves[_sourceToken].balance) >= _amount, "ERR_INVALID_AMOUNT"); syncReserveBalance(_sourceToken); reserves[_targetToken].balance = targetReserveBalance.sub(targetAmount); stakedBalances[_targetToken] = stakedBalances[_targetToken].add(calculateDeficit(externalRate) == 0 ? fee : fee / 2); return (targetAmount, fee); }
1,066,791
./partial_match/1/0x2Ec62769e99b382fC6308e840762a039f6507845/sources/ERC20Token.sol
Transfer token for a specified addresses. from The address to transfer from. to The address to transfer to. value The amount to be transferred./
function _transfer(address from, address to, uint256 value) internal { require(to != address(0), "ERC20: transfer to the zero address"); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); }
3,927,091
/** *Submitted for verification at BscScan.com on 2021-04-11 */ 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor (string memory name, string memory symbol) { _name = name; _symbol = symbol; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return 18; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _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); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // pragma solidity >=0.5.0; interface IUniswapV2ERC20 { 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; } // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface Lottery { //A lottery contract keeps track of who is eligible, so //this must be called on each lottery contract when a user's balance //is updated function addressBalancesUpdated( address user1, uint256 balance1, address user2, uint256 balance2) external; } pragma solidity 0.7.3; // SPDX-License-Identifier: Unlicensed contract XXXToken is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public _burnPool = 0x0000000000000000000000000000000000000000; uint256 private minTokensBeforeSwap; uint256 internal _totalSupply; bool inSwapAndLiquify; uint256 swapAndLiquifyBlockNumber; bool swapAndLiquifyEnabled; bool feesEnabled; address private teamAllocationWalletA = 0x0000000000000000000000000000000000000000; address private teamAllocationWalletB = 0x0000000000000000000000000000000000000000; address private teamAllocationWalletC = 0x0000000000000000000000000000000000000000; address private teamAllocationWalletD = 0x0000000000000000000000000000000000000000; address private teamMasterWallet = 0x0000000000000000000000000000000000000000; address private teamOperationsWallet = 0x0000000000000000000000000000000000000000; address private teamFeesWalletA = 0x0000000000000000000000000000000000000000; address private teamFeesWalletB = 0x0000000000000000000000000000000000000000; address private teamFeesWalletC = 0x0000000000000000000000000000000000000000; address private teamFeesWalletD = 0x0000000000000000000000000000000000000000; address private teamOperationsFeesWallet = 0x0000000000000000000000000000000000000000; address private presaleDeployerWallet = 0x0000000000000000000000000000000000000000; //Lock wallets A to D for 21 days from transferring mapping(address => bool) public lockedWallets; //Set to 21 days after deploy uint256 public lockedWalletsUnlockTime; Lottery public lotteryContractA; Lottery public lotteryContractB; //If this is set to true, the lotteryContractA cannot be changed anymore. bool public lotteryContractALocked; //If this is set to true, the lotteryContractB cannot be changed anymore. bool public lotteryContractBLocked; uint256 private teamFeesA = 75; //Fees are in 100ths of a percent. 0.75% uint256 private teamFeesB = 75; uint256 private teamFeesC = 75; uint256 private teamFeesD = 25; uint256 private teamOperationsFees = 50; uint256 private lotteryContractAFee = 250; uint256 private lotteryContractBFee = 250; uint256 private liquidityFee = 100; uint256 private burnRate = 100; event LotteryContractAUpdated(address addr); event LotteryContractBUpdated(address addr); event LotteryContractALocked(address addr); event LotteryContractBLocked(address addr); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event FeesEnabledUpdated(bool enabled); event SwapTokensFailed( uint256 tokensSwapped ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor( IUniswapV2Router02 _uniswapV2Router, uint256 _minTokensBeforeSwap, bool _feesEnabled ) ERC20("XXX", "$XXX") { //Initial token count is 77,777,777 uint256 teamAllocationWalletATokens = 1555555.54 ether; uint256 teamAllocationWalletBTokens = 1555555.54 ether; uint256 teamAllocationWalletCTokens = 1555555.54 ether; uint256 teamAllocationWalletDTokens = 388888.885 ether; uint256 teamMasterWalletTokens = 45111110.66 ether; uint256 teamOperationsTokens = 2722222.195 ether; uint256 presaleDeployerTokens = 24888888.64 ether; _mint(teamAllocationWalletA, teamAllocationWalletATokens); _mint(teamAllocationWalletB, teamAllocationWalletBTokens); _mint(teamAllocationWalletC, teamAllocationWalletCTokens); _mint(teamAllocationWalletD, teamAllocationWalletDTokens); _mint(teamMasterWallet, teamMasterWalletTokens); _mint(teamOperationsWallet, teamOperationsTokens); _mint(presaleDeployerWallet, presaleDeployerTokens); //Lock team allocation wallets for 21 days lockedWalletsUnlockTime = block.timestamp.add(1814400); lockedWallets[teamAllocationWalletA] = true; lockedWallets[teamAllocationWalletB] = true; lockedWallets[teamAllocationWalletC] = true; lockedWallets[teamAllocationWalletD] = true; // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; updateMinTokensBeforeSwap(_minTokensBeforeSwap); if(_feesEnabled) { setFeesEnabled(); } } //Stores the fees for a transfer, including the total fees struct Fees { uint256 teamFeesATokens; uint256 teamFeesBTokens; uint256 teamFeesCTokens; uint256 teamFeesDTokens; uint256 teamOperationsFeesTokens; uint256 lotteryContractATokens; uint256 lotteryContractBTokens; uint256 liquidityTokens; uint256 burnTokens; uint256 totalFees; } function setLotteryContractA( address addr, bool locked ) external onlyOwner { //Cannot update if already locked require(!lotteryContractALocked); lotteryContractA = Lottery(addr); lotteryContractALocked = locked; emit LotteryContractAUpdated(addr); if(locked) { emit LotteryContractALocked(addr); } } function lockLotteryContractA() external onlyOwner { //Cannot lock if already locked require(!lotteryContractALocked); //Cannot lock if no lottery set require(address(lotteryContractA) != address(0x0)); lotteryContractALocked = true; emit LotteryContractALocked(address(lotteryContractA)); } function setLotteryContractB( address addr, bool locked ) external onlyOwner { //Cannot update if already locked require(!lotteryContractBLocked); require(address(lotteryContractB) == address(0x0)); lotteryContractB = Lottery(addr); lotteryContractBLocked = locked; emit LotteryContractBUpdated(addr); if(locked) { emit LotteryContractBLocked(addr); } } function lockLotteryContractB() external onlyOwner { //Cannot lock if already locked require(!lotteryContractBLocked); //Cannot lock if no lottery set require(address(lotteryContractB) != address(0x0)); lotteryContractBLocked = true; emit LotteryContractBLocked(address(lotteryContractB)); } //Generates a Fee struct for a given amount that is transferred //If a lottery contract is not set, there will be no fees for that (ie, those tokens are not burned) function getFees( uint256 amount ) private view returns (Fees memory) { Fees memory fees; uint totalFees = 0; //Calculate tokens to payout to address and contracts fees.teamFeesATokens = amount.mul(teamFeesA).div(10000); totalFees = totalFees.add(fees.teamFeesATokens); fees.teamFeesBTokens = amount.mul(teamFeesB).div(10000); totalFees = totalFees.add(fees.teamFeesBTokens); fees.teamFeesCTokens = amount.mul(teamFeesC).div(10000); totalFees = totalFees.add(fees.teamFeesCTokens); fees.teamFeesDTokens = amount.mul(teamFeesD).div(10000); totalFees = totalFees.add(fees.teamFeesDTokens); fees.teamOperationsFeesTokens = amount.mul(teamOperationsFees).div(10000); totalFees = totalFees.add(fees.teamOperationsFeesTokens); if(address(lotteryContractA) != address(0x0)) { fees.lotteryContractATokens = amount.mul(lotteryContractAFee).div(10000); totalFees = totalFees.add(fees.lotteryContractATokens); } if(address(lotteryContractB) != address(0x0)) { fees.lotteryContractBTokens = amount.mul(lotteryContractBFee).div(10000); totalFees = totalFees.add(fees.lotteryContractBTokens); } fees.liquidityTokens = amount.mul(liquidityFee).div(10000); totalFees = totalFees.add(fees.liquidityTokens); fees.burnTokens = amount.mul(burnRate).div(10000); totalFees = totalFees.add(fees.burnTokens); fees.totalFees = totalFees; return fees; } //Pays out the fees from the address specified by from function _payoutFees( address from, Fees memory fees ) private { super._transfer(from, teamFeesWalletA, fees.teamFeesATokens); super._transfer(from, teamFeesWalletB, fees.teamFeesBTokens); super._transfer(from, teamFeesWalletC, fees.teamFeesCTokens); super._transfer(from, teamFeesWalletD, fees.teamFeesDTokens); super._transfer(from, teamOperationsFeesWallet, fees.teamOperationsFeesTokens); //Will be 0 if contract not set if(fees.lotteryContractATokens > 0) { super._transfer(from, address(lotteryContractA), fees.lotteryContractATokens); } //Will be 0 if contract not set if(fees.lotteryContractBTokens > 0) { super._transfer(from, address(lotteryContractB), fees.lotteryContractBTokens); } //1% burn rate _burn(from, fees.burnTokens); //The liquidity fee is sent to the contract. Future calls to transfer will add liquidity once it is >= minTokensBeforeSwap super._transfer(from, address(this), fees.liquidityTokens); } //Overrides the superclass implementation to handle custom logic //such as taking fees, burning tokens, and supplying liquidity to PancakeSwap function _transfer( address from, address to, uint256 amount ) internal override { //If wallet is locked then... if(lockedWallets[from]) { //check that enough time has passed to allow transfers require(block.timestamp >= lockedWalletsUnlockTime); } //The team master wallet's tokens are locked forever require(from != teamMasterWallet); //Owner is not taxed if (from == owner() || to == owner()) { super._transfer(from, to, amount); } else { uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= (minTokensBeforeSwap.mul(10 ** decimals())); //Only swap and liquify if >= min balance set to do so, //and have not already swapped this blcok, //and the sender isn't a uniswap pair or lottery contract, //and fees are enabled if ( overMinTokenBalance && !inSwapAndLiquify && block.number > swapAndLiquifyBlockNumber && msg.sender != uniswapV2Pair && msg.sender != address(lotteryContractA) && msg.sender != address(lotteryContractB) && feesEnabled ) { swapAndLiquify(contractTokenBalance); } //Fees must be enabled, and don't take fees when the contract is swapping tokens to add liquidity if(feesEnabled && !inSwapAndLiquify) { Fees memory fees = getFees(amount); amount = amount.sub(fees.totalFees); _payoutFees(from, fees); } //Perform the regular transfer to "to" parameter, finally super._transfer(from, to, amount); uint256 toBalance = balanceOf(to); uint256 fromBalance = balanceOf(from); //Call functions in the lottery contracts to tell them balances updated, //so they can keep track of eligible users _updateLotteryAddressBalances(lotteryContractA, to, toBalance, from, fromBalance); _updateLotteryAddressBalances(lotteryContractB, to, toBalance, from, fromBalance); } } //Calls addressBalancesUpdated for the given lottery, if it has been set //It makes sure that it doesn't pass in the PancakeSwap router address, pair //or lottery itself //because they are not eligible to win the lottery function _updateLotteryAddressBalances( Lottery lottery, address user1, uint256 balance1, address user2, uint256 balance2) private { if(address(lottery) == address(0x0)) { return; } //Don't allow router, pair, or the lottery itself to participate in the lottery if(user1 == address(uniswapV2Router) || user1 == address(uniswapV2Pair) || user1 == address(lottery)) { user1 = address(0x0); } if(user2 == address(uniswapV2Router) || user2 == address(uniswapV2Pair) || user2 == address(lottery)) { user2 = address(0x0); } lottery.addressBalancesUpdated( user1, balance1, user2, balance2); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { swapAndLiquifyBlockNumber = block.number; // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; if(swapTokensForEth(half)) { // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } else { emit SwapTokensFailed(half); } } function swapTokensForEth(uint256 tokenAmount) private returns (bool) { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); //If for whatever reason the swap cannot be made, return false without //failing the whole transaction try uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ) { return true; } catch( bytes memory) { return false; } } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } receive() external payable {} function updateMinTokensBeforeSwap(uint256 _minTokensBeforeSwap) public onlyOwner { minTokensBeforeSwap = _minTokensBeforeSwap; emit MinTokensBeforeSwapUpdated(_minTokensBeforeSwap); } //Fees can only be turned on. Once they are on, they cannot be turned off function setFeesEnabled() public onlyOwner { require(!feesEnabled); feesEnabled = true; emit FeesEnabledUpdated(true); } }
Cannot update if already locked
function setLotteryContractA( address addr, bool locked ) external onlyOwner { require(!lotteryContractALocked); lotteryContractA = Lottery(addr); lotteryContractALocked = locked; emit LotteryContractAUpdated(addr); if(locked) { emit LotteryContractALocked(addr); } }
5,352,616
./full_match/43113/0x76CDc4dd215efeb226570214eF6819057BbC6044/sources/contracts/ExitQueue.sol
work out allocation for the next available epoch Bookkeeping
function join(address _exiter, uint256 _amount) external { require(_amount > 0, "Amount must be > 0"); if (nextUnallocatedEpoch < currentEpoch()) { nextUnallocatedEpoch = currentEpoch(); } User storage user = userData[_exiter]; uint256 unallocatedAmount = _amount; uint256 _nextUnallocatedEpoch = nextUnallocatedEpoch; uint256 nextAvailableEpochForUser = _nextUnallocatedEpoch; if (user.LastExitEpoch > nextAvailableEpochForUser) { nextAvailableEpochForUser = user.LastExitEpoch; } while (unallocatedAmount > 0) { uint256 allocationForEpoch = unallocatedAmount; if (user.Exits[nextAvailableEpochForUser] + allocationForEpoch > maxPerAddress) { allocationForEpoch = maxPerAddress - user.Exits[nextAvailableEpochForUser]; } if (totalPerEpoch[nextAvailableEpochForUser] + allocationForEpoch > maxPerEpoch) { allocationForEpoch = maxPerEpoch - totalPerEpoch[nextAvailableEpochForUser]; } if (allocationForEpoch > 0) { if (user.Amount == 0) { user.FirstExitEpoch = nextAvailableEpochForUser; } user.Amount += allocationForEpoch; user.Exits[nextAvailableEpochForUser] += allocationForEpoch; totalPerEpoch[nextAvailableEpochForUser] += allocationForEpoch; user.LastExitEpoch = nextAvailableEpochForUser; if (totalPerEpoch[nextAvailableEpochForUser] >= maxPerEpoch) { _nextUnallocatedEpoch = nextAvailableEpochForUser; } unallocatedAmount -= allocationForEpoch; } nextAvailableEpochForUser += 1; } SafeERC20.safeTransferFrom(DF, msg.sender, address(this), _amount); emit JoinQueue(_exiter, _amount); }
7,171,873
./full_match/11155111/0x43082Cd06c3747CF5968Fc0a2278749567e1396b/sources/contracts/manifold/creator-core/ERC721CreatorImplementation.sol
See {IERC721CreatorCore-mintBase}./
function mintBase(address to) public virtual override nonReentrant adminRequired returns (uint256) { return _mintBase(to, ""); }
3,798,409
./full_match/1313161554/0x4C101A39ca2D3095DB2507dAdDE736B8E6ed827a/sources/contracts/Treasury.sol
adds token as a supproted rewards token by Treasury supported tokens means any future stream token should be whitelisted here _token stream ERC20 token address
function addSupportedToken(address _token) external pausable(1) onlyRole(TREASURY_MANAGER_ROLE) { require(!isSupportedToken[_token], "TOKEN_ALREADY_EXISTS"); isSupportedToken[_token] = true; emit TokenAdded(_token, msg.sender, block.timestamp); }
13,230,943
pragma solidity ^0.5.16; import "./IERC20.sol"; import "./SafeERC20.sol"; /** * @title KUSDVault stores the Kine off-chain trading system's kUSD. When total vault of synthetic assets in Kine trading system changed, Kine reporter will mint/burn corresponding * kUSD in this vault to ensure kUSD total supply synced with synthetic assets' value. * @author Kine */ contract KUSDVault { using SafeERC20 for IERC20; // @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); // @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); // @notice Emitted when kUSD transferred event TransferKusd(address indexed counterParty, uint amount); // @notice Emitted when Erc20 transferred event TransferErc20(address indexed erc20, address indexed target, uint amount); // @notice Emitted when Ehter transferred event TransferEther(address indexed target, uint amount); // @notice Emitted when Ehter recieved event ReceiveEther(uint amount); // @notice Emitted when operator changed event NewOperator(address oldOperator, address newOperator); // @notice Emitted when counter party changed event NewCounterParty(address oldCounterParty, address newCounterParty); // @notice Emitted when kUSD changed event NewKUSD(address oldKUSD, address newKUSD); address public admin; address public pendingAdmin; address public operator; address public counterParty; IERC20 public kUSD; modifier onlyAdmin() { require(msg.sender == admin, "only admin can call"); _; } modifier onlyOperator() { require(msg.sender == operator, "only operator can call"); _; } constructor(address admin_, address operator_, address counterParty_, address kUSD_) public { admin = admin_; operator = operator_; counterParty = counterParty_; kUSD = IERC20(kUSD_); } // @notice Operator can transfer kUSD to counterParty function transferKusd(uint amount) external onlyOperator { // check balance; uint balance = kUSD.balanceOf(address(this)); require(balance >= amount, "not enough kUSD balance"); // transferKusd kUSD.safeTransfer(counterParty, amount); emit TransferKusd(counterParty, amount); } // @notice Only admin can call function transferErc20(address erc20Addr, address target, uint amount) external onlyAdmin { // check balance; IERC20 erc20 = IERC20(erc20Addr); uint balance = erc20.balanceOf(address(this)); require(balance >= amount, "not enough erc20 balance"); // transfer token erc20.safeTransfer(target, amount); emit TransferErc20(erc20Addr, target, amount); } // @notice Only admin can call function transferEther(address payable target, uint amount) external onlyAdmin { // check balance; require(address(this).balance >= amount, "not enough ether balance"); // transfer ether require(target.send(amount), "transfer failed"); emit TransferEther(target, amount); } // @notice Only admin can set operator function _setOperator(address newOperator) external onlyAdmin { address oldOperator = operator; operator = newOperator; emit NewOperator(oldOperator, newOperator); } // only admin can set counterParty function _setCounterParty(address newCounterParty) external onlyAdmin { address oldCounterParty = counterParty; counterParty = newCounterParty; emit NewCounterParty(oldCounterParty, newCounterParty); } // only admin can set kUSD function _setKUSD(address newKUSD) external onlyAdmin { address oldKUSD = address(kUSD); kUSD = IERC20(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) external onlyAdmin { // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin */ function _acceptAdmin() external { require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } // allow to recieve ether function() external payable { if (msg.value > 0) { emit ReceiveEther(msg.value); } } }
allow to recieve ether
function() external payable { if (msg.value > 0) { emit ReceiveEther(msg.value); } }
12,656,583
./partial_match/1/0x2d64741233100A5529f6A6c244204e460B8Cef6C/sources/pepe.sol
No tax transferIs there tax for sender|receiver?Tax transferNo tax transfer
function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(amount > 1e9, "Min transfer amt"); uint256 _tax; if (_isExcludedFromFeeWallet[from] || _isExcludedFromFeeWallet[to]) { _tax = 0; require( launch != 0 && amount <= maxTxAmount, "Launch / Max TxAmount 1% at launch" ); if ( !_isExcludedFromMaxWallet[to] ) { require( _balance[to] + amount <= maxWalletAmount, "Exceeds max wallet balance" ); } if (inSwapAndLiquify == 1) { _balance[from] -= amount; _balance[to] += amount; emit Transfer(from, to, amount); return; } if (from == uniswapV2Pair) { _tax = buyTax + lpTax; uint256 tokensToSwap = _balance[address(this)]; if (tokensToSwap > minSwap && inSwapAndLiquify == 0) { if (tokensToSwap > maxSwap) { tokensToSwap = maxSwap; } uint liqidityToken = (tokensToSwap * lpTax) / (((buyTax + sellTax) / 2 ) + lpTax ); uint tokensTosell = tokensToSwap - liqidityToken; inSwapAndLiquify = 1; address[] memory path = new address[](2); path[0] = address(this); path[1] = WETH; uniswapV2Router .swapExactTokensForETHSupportingFeeOnTransferTokens( tokensTosell, 0, path, marketingWallet, block.timestamp ); if ( liqidityToken > 0) { uniswapV2Router .swapExactTokensForETHSupportingFeeOnTransferTokens( liqidityToken / 2, 0, path, address(this), block.timestamp ); uint newBal = address(this).balance; uniswapV2Router liqidityToken / 2, 0, 0, owner(), block.timestamp ); } inSwapAndLiquify = 0; } _tax = sellTax + lpTax; _tax = 0; } } if (_tax != 0) { uint256 taxTokens = (amount * _tax) / 100; uint256 transferAmount = amount - taxTokens; _balance[from] -= amount; _balance[to] += transferAmount; _balance[address(this)] += taxTokens; emit Transfer(from, address(this), taxTokens); emit Transfer(from, to, transferAmount); _balance[from] -= amount; _balance[to] += amount; emit Transfer(from, to, amount); } }
2,888,391
pragma solidity ^0.8.0; import "./MintableTokenDelegate.sol"; import "./RuleEngineDelegate.sol"; import "./SeizableDelegate.sol"; import "./FreezableDelegate.sol"; import "./LockableDelegate.sol"; import "./KYCOnlyTransferabilityDelegate.sol"; /** * @title KYCOnly Token Delegate * @dev KYCOnly Token Delegate * * @author Cyril Lapinte - <[email protected]> * SPDX-License-Identifier: MIT * * Error messagesa * KOT01: The token must not be locked * KOT02: The addresses must not be frozen * KOT03: The transfer rules must be valid * KOT04: The sender or receiver are not valid */ contract KYCOnlyTokenDelegate is KYCOnlyTransferabilityDelegate, RuleEngineDelegate, SeizableDelegate, FreezableDelegate, LockableDelegate, MintableTokenDelegate { uint256 internal constant AUDIT_CONFIG_REQUIREMENTS = 1; // 1- Transfer Limits /** * @dev check config requirements **/ function checkConfigurations(uint256[] calldata _auditConfigurationIds) override public pure returns (bool) { return (_auditConfigurationIds.length >= AUDIT_CONFIG_REQUIREMENTS); } /** * @dev transfer */ function transferInternal(STransferData memory _transferData) override internal returns (bool) { require(!isLocked(_transferData), "KOT01"); require(!isFrozen(_transferData), "KOT02"); require(areTransferRulesValid(_transferData), "KOT03"); STransferAuditData memory _transferAuditData = prepareAuditInternal(_transferData); require(hasTransferValidUsers(_transferData, _transferAuditData) == TransferCode.OK, "KOT04"); return super.transferInternal(_transferData); } /** * @dev can transfer */ function canTransferInternal(STransferData memory _transferData) override internal view returns (TransferCode code) { if (isLocked(_transferData)) { return TransferCode.LOCKED; } if (isFrozen(_transferData)) { return TransferCode.FROZEN; } if (!areTransferRulesValid(_transferData)) { return TransferCode.RULE; } STransferAuditData memory _transferAuditData = prepareAuditInternal(_transferData); code = hasTransferValidUsers(_transferData, _transferAuditData); return (code == TransferCode.OK) ? super.canTransferInternal(_transferData) : code; } }
can transfer/
function canTransferInternal(STransferData memory _transferData) override internal view returns (TransferCode code) { if (isLocked(_transferData)) { return TransferCode.LOCKED; } if (isFrozen(_transferData)) { return TransferCode.FROZEN; } if (!areTransferRulesValid(_transferData)) { return TransferCode.RULE; } STransferAuditData memory _transferAuditData = prepareAuditInternal(_transferData); code = hasTransferValidUsers(_transferData, _transferAuditData); return (code == TransferCode.OK) ? super.canTransferInternal(_transferData) : code; }
12,758,153
pragma solidity ^0.8.0; import "./Administered.sol"; contract DEHR is Administered{ enum BlodType{ A_POSITIVE, A_NEGATIVE, B_POSITIVE, B_NEGATIVE, AB_POSITIVE, AB_NEGATIVE, O_POSITIVE, O_NEGATIVE } struct UserInfo{ uint date; string hashing; } enum OfferStatus { AVAILABLE, PENDING, ACCEPTED, REJECTED, Donated, CANCEL } struct DonateOffer{ string gen; BlodType blodType; string someOtherInfo; bool done; OfferStatus offerStatus; address donnerAddress; address organapplicant; } mapping (uint => DonateOffer) private donateOffers; mapping (uint => address) private donners; mapping (uint => address) private organapplicant; mapping (address => UserInfo[]) private userInfo; int32 private donnersCount; int32 private totalDonateOffer; int32 private userCount; int32 private medicalStuffCount; constructor() public { /* Here, set the owner as the person who instantiated the contract and set your idCount to 0. */ _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); //_setupRole(MARKET_ADMIN_ROLE, msg.sender); _setRoleAdmin(USER_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(MEDICAL_STUFF_ROLE, DEFAULT_ADMIN_ROLE); } function AddInfo(string hash) public { userInfo[msg.sender].push(now, hash); } function GetGenHashInfo(string hash) public { return userInfo[msg.sender][0].hashing; } function CreateDonateOffer( string _gen, BlodType _blodType, string _someOtherInfo, OfferStatus _offerStatus ) public { DonateOffer donateOffer; donateOffer.gen=_gen; donateOffer.blodType=_blodType; donateOffer.someOtherInfo=_someOtherInfo; donateOffer.OfferStatus= _offerStatus; } function getDonateOffer() public returns(DonateOffer[]) { return donateOffer[msg.sender]; } function getDonateOffer() public { } function getMatchedDonateOffer() public returns(DonateOffer[]) { UserInfo currentUserInfo=userInfo[msg.sender]; // currentUserInfo.hashing read from ipfs for(int i=0; i< totalDonateOffer; i++ ) { for(int j=0; i< donnersCount; j++ ) { donateOffers[i][donners[j]]; //moghayese } } //return null; } function DonateRequest(uint donateOfferId) public { donateOffers[donateOfferId].organapplicant=msg.sender; donateOffers[donateOfferId].offerStatus=OfferStatus.PENDING; } function AcceptOffer(uint donateOfferId) public { donateOffers[donateOfferId].offerStatus=OfferStatus.ACCEPTED; } function RejectOffer(uint donateOfferId) public { donateOffers[donateOfferId].offerStatus=OfferStatus.REJECTED; } function CancelOffer(uint donateOfferId) public { donateOffers[donateOfferId].offerStatus=OfferStatus.CANCEL; } function ReadUserInfo(address _userAddress) onlyPermitedUser public { //read from ipfs } }
currentUserInfo.hashing read from ipfsmoghayese
function getMatchedDonateOffer() public returns(DonateOffer[]) { UserInfo currentUserInfo=userInfo[msg.sender]; for(int i=0; i< totalDonateOffer; i++ ) { for(int j=0; i< donnersCount; j++ ) { donateOffers[i][donners[j]]; } }
6,400,995
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.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.4.22 <0.9.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.4.22 <0.9.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.4.22 <0.9.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract WallStreetChads is ERC721Enumerable, Ownable { using Strings for uint256; uint256 public maxPerTransactionGeneralSale = 20; uint256 public maxPerUserPreSale = 1; uint256 public maxTokensGeneralSale = 10000; uint256 public maxTokensPreSale = 500; uint256 public reservedChads = 100; uint256 public chadPrice = 0.08 ether; string public baseTokenURI; string public loadingURI; bool public generalSaleIsActive = false; bool public preSaleIsActive = false; // Events event ValueReceived(address user, uint amount); constructor (string memory _name, string memory _symbol, string memory _loadingURI) ERC721(_name, _symbol) { setLoadingURI(_loadingURI); _safeMint(msg.sender, 0); _safeMint(msg.sender, 1); _safeMint(msg.sender, 2); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; Address.sendValue(payable(msg.sender), balance); } function pauseGeneralSale() public onlyOwner { generalSaleIsActive = false; } function unpauseGeneralSale() public onlyOwner { generalSaleIsActive = true; } function pausePreSale() public onlyOwner { preSaleIsActive = false; } function unpausePreSale() public onlyOwner { preSaleIsActive = true; } // Minting & Transfer Related Functions function mintWallStreetChadsGeneralSale(uint256 _amountToMint) public payable { uint256 supply = totalSupply(); require(generalSaleIsActive, 'Wall Street Chads: Sale must be active to mint a Chad, patient you must be.'); require(_amountToMint <= maxPerTransactionGeneralSale, 'Wall Street Chads: Can only mint 20 Chads at a time, you degenerate.'); require((chadPrice * _amountToMint) <= msg.value, 'Wall Street Chads: Ether value sent is not correct, go raise some funds and come back to us.'); require((supply + _amountToMint) <= (maxTokensGeneralSale - reservedChads), 'Wall Street Chads: Exceeds Wall Street Chads supply for sale.'); for (uint256 i=0; i < _amountToMint; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } } function mintWallStreetChadsPreSale() public payable { uint256 supply = totalSupply(); uint256 numberOfWallStreetChadsCurrentlyOwned = balanceOf(msg.sender); // Potentially remove this if statement require(preSaleIsActive, 'Wall Street Chads: Pre-sale must be active to mint a Chad, patient you must be.'); require(!generalSaleIsActive, 'Wall Street Chads: General sale must be inactive throughout the pre-sale.'); require(numberOfWallStreetChadsCurrentlyOwned < maxPerUserPreSale, 'Wall Street Chads: You can only mint one WSC per address during the pre-sale.'); require(chadPrice <= msg.value, 'Wall Street Chads: Ether value sent is not correct, go raise some funds and come back to us.'); require((supply + 1) <= maxTokensPreSale, 'Wall Street Chads: Exceeds Wall Street Chads supply for pre-sale.'); uint256 newTokenId = supply; _safeMint(msg.sender, newTokenId); } function giveAway(address _to, uint256 _amount) external onlyOwner { require(_amount <= reservedChads, 'Wall Street Chads: Request exceeds reserved supply of our legends.'); for (uint256 i=0; i < _amount; i++) { uint256 mintIndex = totalSupply(); _safeMint(_to, mintIndex); } // Subtract the number reservedChads -= _amount; } function walletOfOwner(address _owner) public view returns(uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory arrayOfTokenId = new uint256[](tokenCount); for (uint256 i=0; i < tokenCount; i++) { arrayOfTokenId[i] = tokenOfOwnerByIndex(_owner, i); } return arrayOfTokenId; } function numbersOfWallStreetChadsOwnedBy(address _owner) public view returns (uint256) { uint256 numberOfTokensOwned = balanceOf(_owner); return numberOfTokensOwned; } /* * * Price related functions * */ function getPrice() public view returns (uint256) { return chadPrice; } // @dev - In case ETH fluctuates heavily function setPrice(uint256 _newPrice) public onlyOwner { chadPrice = _newPrice; } /* * * URI related functions * */ function baseURI() public view returns (string memory) { return baseTokenURI; } function setBaseURI(string memory _baseURI) public onlyOwner { baseTokenURI = _baseURI; } function removeBaseURI() public onlyOwner { baseTokenURI = ''; } function setLoadingURI(string memory _loadingURI) public onlyOwner { loadingURI = _loadingURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId), 'Wall Street Chads: Query made for nonexistent token.'); string memory tokenURISuffix = '.json'; string memory tokenIdentifier = string(abi.encodePacked(Strings.toString(_tokenId), tokenURISuffix)); string memory base = baseURI(); // If no base URI, then we actually have not revealed our ambitious Wall Street Chads to the world. if (bytes(base).length == 0) { return loadingURI; } // If both are set, concatenate the baseURI and tokenIdentifier (via abi.encodePakcked). if (bytes(tokenIdentifier).length > 0) { return string(abi.encodePacked(base, tokenIdentifier)); } // If there is a baseURI but no tokenIdentifier, concatenate the tokenId to the baseURI return string(abi.encodePacked(base, Strings.toString(_tokenId))); } receive() external payable { emit ValueReceived(msg.sender, msg.value); } fallback() external payable { } }
Potentially remove this if statement
function mintWallStreetChadsPreSale() public payable { uint256 supply = totalSupply(); uint256 numberOfWallStreetChadsCurrentlyOwned = balanceOf(msg.sender); require(preSaleIsActive, 'Wall Street Chads: Pre-sale must be active to mint a Chad, patient you must be.'); require(!generalSaleIsActive, 'Wall Street Chads: General sale must be inactive throughout the pre-sale.'); require(numberOfWallStreetChadsCurrentlyOwned < maxPerUserPreSale, 'Wall Street Chads: You can only mint one WSC per address during the pre-sale.'); require(chadPrice <= msg.value, 'Wall Street Chads: Ether value sent is not correct, go raise some funds and come back to us.'); require((supply + 1) <= maxTokensPreSale, 'Wall Street Chads: Exceeds Wall Street Chads supply for pre-sale.'); uint256 newTokenId = supply; _safeMint(msg.sender, newTokenId); }
1,268,340
pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ /*@CTK SafeMath_mul @tag spec @post __reverted == __has_assertion_failure @post __has_assertion_failure == __has_overflow @post __reverted == false -> c == a * b @post msg == msg__post */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ /*@CTK SafeMath_div @tag spec @pre b != 0 @post __reverted == __has_assertion_failure @post __has_overflow == true -> __has_assertion_failure == true @post __reverted == false -> __return == a / b @post msg == msg__post */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ /*@CTK SafeMath_sub @tag spec @post __reverted == __has_assertion_failure @post __has_overflow == true -> __has_assertion_failure == true @post __reverted == false -> __return == a - b @post msg == msg__post */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ /*@CTK SafeMath_add @tag spec @post __reverted == __has_assertion_failure @post __has_assertion_failure == __has_overflow @post __reverted == false -> c == a + b @post msg == msg__post */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ /*@CTK owner_set_on_success @pre __reverted == false -> __post.owner == owner */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ 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. */ /*@CTK transferOwnership @post __reverted == false -> (msg.sender == owner -> __post.owner == newOwner) @post (owner != msg.sender) -> (__reverted == true) @post (newOwner == address(0)) -> (__reverted == true) */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @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); } /** * @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 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. */ /*@CTK transfer_success @pre _to != address(0) @pre balances[msg.sender] >= _value @pre __reverted == false @post __reverted == false @post __return == true */ /*@CTK transfer_same_address @tag no_overflow @pre _to == msg.sender @post this == __post */ /*@CTK transfer_conditions @tag assume_completion @pre _to != msg.sender @post __post.balances[_to] == balances[_to] + _value @post __post.balances[msg.sender] == balances[msg.sender] - _value */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ /*@CTK balanceOf @post __reverted == false @post __return == balances[_owner] */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function balanceOf(address _owner) public view returns (uint256) { 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)) 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 */ /*@CTK transferFrom @tag assume_completion @pre _from != _to @post __return == true @post __post.balances[_to] == balances[_to] + _value @post __post.balances[_from] == balances[_from] - _value @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ /*@CTK approve_success @post _value == 0 -> __reverted == false @post allowed[msg.sender][_spender] == 0 -> __reverted == false */ /*@CTK approve @tag assume_completion @post __post.allowed[msg.sender][_spender] == _value */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ /*@CTK CtkIncreaseApprovalEffect @tag assume_completion @post __post.allowed[msg.sender][_spender] == allowed[msg.sender][_spender] + _addedValue @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ /*@CTK CtkDecreaseApprovalEffect_1 @pre allowed[msg.sender][_spender] >= _subtractedValue @tag assume_completion @post __post.allowed[msg.sender][_spender] == allowed[msg.sender][_spender] - _subtractedValue @post __has_overflow == false */ /*@CTK CtkDecreaseApprovalEffect_2 @pre allowed[msg.sender][_spender] < _subtractedValue @tag assume_completion @post __post.allowed[msg.sender][_spender] == 0 @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract IoTeXNetwork is StandardToken, Pausable { string public constant name = "IoTeX Network"; string public constant symbol = "IOTX"; uint8 public constant decimals = 18; modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this) ); _; } function IoTeXNetwork(uint tokenTotalAmount) { totalSupply_ = tokenTotalAmount; balances[msg.sender] = tokenTotalAmount; emit Transfer(address(0x0), msg.sender, tokenTotalAmount); } /*@CTK CtkTransferNoEffect @post (_to == address(0)) \/ (paused == true) -> __reverted == true */ /*@CTK CtkTransferEffect @pre __reverted == false @pre balances[msg.sender] >= _value @pre paused == false @pre __return == true @pre msg.sender != _to @post __post.balances[_to] == balances[_to] + _value @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function transfer(address _to, uint _value) whenNotPaused validDestination(_to) returns (bool) { return super.transfer(_to, _value); } /*@CTK CtkTransferFromNoEffect @post (_to == address(0)) \/ (paused == true) -> __reverted == true */ /*@CTK CtkTransferFromEffect @tag assume_completion @pre _from != _to @post __post.balances[_to] == balances[_to] + _value @post __post.balances[_from] == balances[_from] - _value @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function transferFrom(address _from, address _to, uint _value) whenNotPaused validDestination(_to) returns (bool) { return super.transferFrom(_from, _to, _value); } /*@CTK CtkApproveNoEffect @post (paused == true) -> __post == this */ /*@CTK CtkApprove @tag assume_completion @post __post.allowed[msg.sender][_spender] == _value */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } /*@CTK CtkIncreaseApprovalNoEffect @post (paused == true) -> __reverted == true */ /*@CTK CtkIncreaseApprovalEffect @pre paused == false @tag assume_completion @post __post.allowed[msg.sender][_spender] == allowed[msg.sender][_spender] + _addedValue @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /*@CTK CtkDecreaseApprovalNoEffect @post (paused == true) -> __reverted == true */ /*@CTK CtkDecreaseApprovalEffect @pre allowed[msg.sender][_spender] >= _subtractedValue @tag assume_completion @post __post.allowed[msg.sender][_spender] == allowed[msg.sender][_spender] - _subtractedValue @post __has_overflow == false */ /* CertiK Smart Labelling, for more details visit: https://certik.org */ function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } }
Function to check the amount of tokens that an owner allowed to a spender. _owner address The address which owns the funds. _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]; } @post __post.allowed[msg.sender][_spender] == allowed[msg.sender][_spender] + _addedValue @post __has_overflow == false
6,519,963
pragma solidity ^0.4.23; /** * @title ERC20 interface */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer( address indexed from, address indexed to, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC827 interface, an extension of ERC20 token standard * * @dev Interface of a ERC827 token, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. */ contract ERC827 is ERC20 { function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool); function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool); function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;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 Standard ERC20 token * */ contract ERC20Token is ERC20{ using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title ERC827, an extension of ERC20 token standard * * @dev Implementation the ERC827, following the ERC20 standard with extra * @dev methods to transfer value and data and execute calls in transfers and * @dev approvals. * * @dev Uses OpenZeppelin StandardToken. */ contract ERC827Token is ERC827, ERC20Token { /** * @dev Addition to ERC20 token methods. It allows to * @dev approve the transfer of value and execute a call with the sent data. * * @dev Beware that changing an allowance with this method brings the risk that * @dev someone may use both the old and the new allowance by unfortunate * @dev transaction ordering. One possible solution to mitigate this race condition * @dev is to first reduce the spender&#39;s allowance to 0 and set the desired value * @dev afterwards: * @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @param _spender The address that will spend the funds. * @param _value The amount of tokens to be spent. * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function approveAndCall( address _spender, uint256 _value, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); // solium-disable-next-line security/no-call-value require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens to a specified * @dev address and execute a call with the sent data on the same transaction * * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferAndCall( address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to ERC20 token methods. Transfer tokens from one address to * @dev another and make a contract call on the same transaction * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amout of tokens to be transferred * @param _data ABI-encoded contract call to call `_to` address. * * @return true if the call function was executed successfully */ function transferFromAndCall( address _from, address _to, uint256 _value, bytes _data ) public payable returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To increment * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApprovalAndCall( address _spender, uint _addedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call.value(msg.value)(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * @dev an owner allowed to a spender and execute a call with the sent data. * * @dev approve should be called when allowed[_spender] == 0. To decrement * @dev allowed value is better to use this function to avoid 2 calls (and wait until * @dev the first transaction is mined) * @dev From MonolithDAO Token.sol * * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApprovalAndCall( address _spender, uint _subtractedValue, bytes _data ) public payable returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call.value(msg.value)(_data)); return true; } } /** * @title Burnable and Pause Token * @dev StandardToken modified with pausable transfers. **/ contract PauseBurnableERC827Token is ERC827Token, Ownable{ using SafeMath for uint256; event Pause(); event Unpause(); event PauseOperatorTransferred(address indexed previousOperator,address indexed newOperator); event Burn(address indexed burner, uint256 value); bool public paused = false; address public pauseOperator; /** * @dev Throws if called by any account other than the owner. */ modifier onlyPauseOperator() { require(msg.sender == pauseOperator || msg.sender == owner); _; } /** * @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 The constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { pauseOperator = msg.sender; } /** * @dev called by the operator to set the new operator to pause the token */ function transferPauseOperator(address newPauseOperator) onlyPauseOperator public { require(newPauseOperator != address(0)); emit PauseOperatorTransferred(pauseOperator, newPauseOperator); pauseOperator = newPauseOperator; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyPauseOperator whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyPauseOperator whenPaused public { paused = false; emit Unpause(); } function transfer(address _to,uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from,address _to,uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender,uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender,uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender,uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public whenNotPaused { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal{ require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); // Subtract from the sender totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public whenNotPaused { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract ICOTH is PauseBurnableERC827Token { string public constant name = "ICOTH"; string public constant symbol = "i"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 10000000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } }
no need to require value <= totalSupply, since that would imply the sender&39;s balance is greater than the totalSupply, which should be an assertion failure
function _burn(address _who, uint256 _value) internal{ require(_value <= balances[_who]); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); }
2,405,203
./full_match/1/0xf7016313b51C73092450a226FA7c4B3bB9Da0DbE/sources/contracts/NFTPersonalNameSignatureCollection.sol
mapping for tokenid -> namehash nameHash -> address nameHash -> records
{ Name errors error Unauthorized(); error AlreadyRegistered(); Name Registry & records mapping(uint256 => bytes32) public names; mapping(bytes32 => address) public domains; mapping(bytes32 => string) public records; Constructor constructor( string memory _name, string memory _symbol, address _royaltyRecipient, uint128 _royaltyBps, address _primarySaleRecipient pragma solidity ^0.8.0; import {StringUtils} from "./libraries/StringUtils.sol"; ) ERC721Base(_name, _symbol, _royaltyRecipient, _royaltyBps) { _setupPrimarySaleRecipient(_primarySaleRecipient); } Signature minting logic function mintWithSignature( MintNameRequest calldata _req, bytes calldata _signature ) external payable virtual override returns (address signer) { require(_req.quantity == 1, "quantiy must be 1"); uint256 tokenIdToMint = nextTokenIdToMint(); signer = _processRequest(_req, _signature); address receiver = _req.to; if (domains[_req.nameHash] != address(0)) revert AlreadyRegistered(); require(domains[_req.nameHash] == address(0)); _collectPriceOnClaim( _req.primarySaleRecipient, _req.quantity, _req.currency, _req.pricePerToken ); if (_req.royaltyRecipient != address(0) && _req.royaltyBps != 0) { _setupRoyaltyInfoForToken( tokenIdToMint, _req.royaltyRecipient, _req.royaltyBps ); } _safeMint(receiver, _req.quantity); domains[_req.nameHash] = msg.sender; names[tokenIdToMint] = _req.nameHash; emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } function mintWithSignature( MintNameRequest calldata _req, bytes calldata _signature ) external payable virtual override returns (address signer) { require(_req.quantity == 1, "quantiy must be 1"); uint256 tokenIdToMint = nextTokenIdToMint(); signer = _processRequest(_req, _signature); address receiver = _req.to; if (domains[_req.nameHash] != address(0)) revert AlreadyRegistered(); require(domains[_req.nameHash] == address(0)); _collectPriceOnClaim( _req.primarySaleRecipient, _req.quantity, _req.currency, _req.pricePerToken ); if (_req.royaltyRecipient != address(0) && _req.royaltyBps != 0) { _setupRoyaltyInfoForToken( tokenIdToMint, _req.royaltyRecipient, _req.royaltyBps ); } _safeMint(receiver, _req.quantity); domains[_req.nameHash] = msg.sender; names[tokenIdToMint] = _req.nameHash; emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req); } _setTokenURI(tokenIdToMint, _req.uri); Name Registry functions function getAddress(string calldata nameHashStr) public view returns (address) { bytes32 nameHash = bytes32(abi.encodePacked(nameHashStr)); return domains[nameHash]; } function valid(string calldata name) public pure returns (bool) { return StringUtils.strlen(name) >= 3; } function setRecord(string calldata nameHashStr, string calldata record) public { bytes32 nameHash = bytes32(abi.encodePacked(nameHashStr)); if (msg.sender != domains[nameHash]) revert Unauthorized(); require(domains[nameHash] == msg.sender); records[nameHash] = record; } function getRecord(string calldata nameHashStr) public view returns (string memory) { bytes32 nameHash = bytes32(abi.encodePacked(nameHashStr)); return records[nameHash]; } Internal functions function _canSignMintRequest(address _signer) internal view virtual override returns (bool) { return _signer == owner(); } function _canSetPrimarySaleRecipient() internal view virtual override returns (bool) { return msg.sender == owner(); } function _collectPriceOnClaim( address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "Must send total price."); } address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient; CurrencyTransferLib.transferCurrency( _currency, msg.sender, saleRecipient, totalPrice ); } function _collectPriceOnClaim( address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "Must send total price."); } address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient; CurrencyTransferLib.transferCurrency( _currency, msg.sender, saleRecipient, totalPrice ); } function _collectPriceOnClaim( address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal virtual { if (_pricePerToken == 0) { return; } uint256 totalPrice = _quantityToClaim * _pricePerToken; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { require(msg.value == totalPrice, "Must send total price."); } address saleRecipient = _primarySaleRecipient == address(0) ? primarySaleRecipient() : _primarySaleRecipient; CurrencyTransferLib.transferCurrency( _currency, msg.sender, saleRecipient, totalPrice ); } }
3,021,899
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {IPolicyPool} from "../interfaces/IPolicyPool.sol"; import {PolicyPoolComponent} from "./PolicyPoolComponent.sol"; import {IEToken} from "../interfaces/IEToken.sol"; import {IPolicyPoolConfig} from "../interfaces/IPolicyPoolConfig.sol"; import {IInsolvencyHook} from "../interfaces/IInsolvencyHook.sol"; import {WadRayMath} from "./WadRayMath.sol"; /** * @title Ensuro ERC20 EToken - interest-bearing token * @dev Implementation of the interest/earnings bearing token for the Ensuro protocol. * The _scaleFactor scales the balances stored in _balances. _scaleFactor grows continuoulsly at * _tokenInterestRate. * Every operation that changes the utilization rate (_scr/totalSupply) or the _scrInterestRate, updates * first the _scaleFactor accumulating the interest accrued since _lastScaleUpdate. * @custom:security-contact [email protected] * @author Ensuro */ contract EToken is PolicyPoolComponent, IERC20Metadata, IEToken { uint256 public constant MIN_SCALE = 1e17; // 0.0000000001 == 1e-10 in ray using WadRayMath for uint256; uint256 internal constant SECONDS_PER_YEAR = 365 days; // Attributes taken from ERC20 mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; // non-scaled totalSupply string private _name; string private _symbol; uint40 internal _expirationPeriod; // in seconds, the maximum duration of policies this eToken can back up uint256 internal _scaleFactor; // in Ray uint40 internal _lastScaleUpdate; uint256 internal _scr; // in Wad - Capital locked as Solvency Capital Requirement of backed up policies uint256 internal _scrInterestRate; // in Ray - Interest rate received in exchange of solvency capital uint256 internal _tokenInterestRate; // in Ray - Overall interest rate of the token uint256 internal _liquidityRequirement; // in Ray - Liquidity requirement to lock more than SCR uint256 internal _maxUtilizationRate; // in Ray - Maximum SCR/totalSupply rate for backup up new policies uint256 internal _poolLoan; // in Wad - Capital that was used to pay defaults of the premium pool. Took as a loan. uint256 internal _poolLoanInterestRate; // in Ray uint256 internal _poolLoanScale; // in Ray uint40 internal _poolLoanLastUpdate; bool internal _acceptAllRMs; // By defaults, accepts (backs up) any RiskModule; // Exceptions to the accept all or accept none policy defined before mapping(address => bool) internal _acceptExceptions; event PoolLoan(uint256 value); event PoolLoanRepaid(uint256 value); modifier onlyAssetManager() { require( _msgSender() == address(_policyPool.config().assetManager()), "The caller must be the PolicyPool's AssetManager" ); _; } modifier validateParamsAfterChange() { _; _validateParameters(); } /// @custom:oz-upgrades-unsafe-allow constructor // solhint-disable-next-line no-empty-blocks constructor(IPolicyPool policyPool_) PolicyPoolComponent(policyPool_) {} /** * @dev Initializes the eToken * @param expirationPeriod Maximum expirationPeriod (from block.timestamp) of policies to be accepted * @param liquidityRequirement_ Liquidity requirement to allow withdrawal (in Ray - default=1 Ray) * @param maxUtilizationRate_ Max utilization rate (scr/totalSupply) (in Ray - default=1 Ray) * @param poolLoanInterestRate_ Rate of loans givencrto the policy pool (in Ray) * @param name_ Name of the eToken * @param symbol_ Symbol of the eToken */ function initialize( string memory name_, string memory symbol_, uint40 expirationPeriod, uint256 liquidityRequirement_, uint256 maxUtilizationRate_, uint256 poolLoanInterestRate_ ) public initializer { __PolicyPoolComponent_init(); __EToken_init_unchained( name_, symbol_, expirationPeriod, liquidityRequirement_, maxUtilizationRate_, poolLoanInterestRate_ ); } // solhint-disable-next-line func-name-mixedcase function __EToken_init_unchained( string memory name_, string memory symbol_, uint40 expirationPeriod, uint256 liquidityRequirement_, uint256 maxUtilizationRate_, uint256 poolLoanInterestRate_ ) internal initializer { _name = name_; _symbol = symbol_; _expirationPeriod = expirationPeriod; _scaleFactor = WadRayMath.ray(); _lastScaleUpdate = uint40(block.timestamp); _scr = 0; _scrInterestRate = 0; _tokenInterestRate = 0; _liquidityRequirement = liquidityRequirement_; _maxUtilizationRate = maxUtilizationRate_; _acceptAllRMs = true; _poolLoan = 0; _poolLoanInterestRate = poolLoanInterestRate_; _poolLoanScale = WadRayMath.ray(); _poolLoanLastUpdate = uint40(block.timestamp); _validateParameters(); } // runs validation on EToken parameters function _validateParameters() internal view { require( _liquidityRequirement >= 8e26 && _liquidityRequirement <= 13e26, "Validation: liquidityRequirement must be [0.8, 1.3]" ); require( _maxUtilizationRate >= 5e26 && _maxUtilizationRate <= WadRayMath.RAY, "Validation: maxUtilizationRate must be [0.5, 1]" ); require(_poolLoanInterestRate <= 5e26, "Validation: poolLoanInterestRate must be <= 50%"); } /*** BEGIN ERC20 methods - mainly copied from OpenZeppelin but changes in events and scaledAmount */ /** * @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 * 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 override returns (uint8) { return _policyPool.currency().decimals(); } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply.wadToRay().rayMul(_calculateCurrentScale()).rayToWad(); } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { uint256 principalBalance = _balances[account]; if (principalBalance == 0) return 0; return principalBalance.wadToRay().rayMul(_calculateCurrentScale()).rayToWad(); } /** * @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, "EToken: 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, "EToken: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function _scaleAmount(uint256 amount) internal view returns (uint256) { return amount.wadToRay().rayDiv(_calculateCurrentScale()).rayToWad(); } /** * @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), "EToken: transfer from the zero address"); require(recipient != address(0), "EToken: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 scaledAmount = _scaleAmount(amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= scaledAmount, "EToken: transfer amount exceeds balance"); _balances[sender] = senderBalance - scaledAmount; _balances[recipient] += scaledAmount; 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), "EToken: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); uint256 scaledAmount = _scaleAmount(amount); _totalSupply += scaledAmount; _balances[account] += scaledAmount; 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), "EToken: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 scaledAmount = _scaleAmount(amount); uint256 accountBalance = _balances[account]; require(accountBalance >= scaledAmount, "EToken: burn amount exceeds balance"); _balances[account] = accountBalance - scaledAmount; _totalSupply -= scaledAmount; 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), "EToken: approve from the zero address"); require(spender != address(0), "EToken: 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 { require( from == address(0) || to == address(0) || address(policyPool().config().lpWhitelist()) == address(0) || policyPool().config().lpWhitelist().acceptsTransfer(this, from, to, amount), "Transfer not allowed - Liquidity Provider not whitelisted" ); } /*** END ERC20 methods - mainly copied from OpenZeppelin but changes in events and scaledAmount */ function _updateCurrentScale() internal { if (uint40(block.timestamp) == _lastScaleUpdate) return; _scaleFactor = _calculateCurrentScale(); require(_scaleFactor >= MIN_SCALE, "Scale too small, can lead to rounding errors"); _lastScaleUpdate = uint40(block.timestamp); } function _updateTokenInterestRate() internal { uint256 totalSupply_ = this.totalSupply().wadToRay(); if (totalSupply_ == 0) _tokenInterestRate = 0; else _tokenInterestRate = _scrInterestRate.rayMul(_scr.wadToRay()).rayDiv(totalSupply_); } function _calculateCurrentScale() internal view returns (uint256) { if (uint40(block.timestamp) <= _lastScaleUpdate) return _scaleFactor; uint256 timeDifference = block.timestamp - _lastScaleUpdate; return _scaleFactor.rayMul( ((_tokenInterestRate * timeDifference) / SECONDS_PER_YEAR) + WadRayMath.ray() ); } function getCurrentScale(bool updated) public view returns (uint256) { if (updated) return _calculateCurrentScale(); else return _scaleFactor; } function ocean() public view virtual override returns (uint256) { uint256 totalSupply_ = this.totalSupply(); if (totalSupply_ > _scr) return totalSupply_ - _scr; else return 0; } function oceanForNewScr() public view virtual override returns (uint256) { uint256 totalSupply_ = this.totalSupply(); if (totalSupply_ > _scr) return (totalSupply_ - _scr).wadMul(_maxUtilizationRate.rayToWad()); else return 0; } function scr() public view virtual override returns (uint256) { return _scr; } function scrInterestRate() public view returns (uint256) { return _scrInterestRate; } function tokenInterestRate() public view returns (uint256) { return _tokenInterestRate; } function liquidityRequirement() public view returns (uint256) { return _liquidityRequirement; } function maxUtilizationRate() public view returns (uint256) { return _maxUtilizationRate; } function utilizationRate() public view returns (uint256) { return _scr.wadDiv(this.totalSupply()).wadToRay(); } function lockScr(uint256 policyInterestRate, uint256 scrAmount) external override onlyPolicyPool { require(scrAmount <= this.ocean(), "Not enought OCEAN to cover the SCR"); _updateCurrentScale(); if (_scr == 0) { _scr = scrAmount; _scrInterestRate = policyInterestRate; } else { uint256 origScr = _scr.wadToRay(); _scr += scrAmount; _scrInterestRate = (_scrInterestRate.rayMul(origScr) + policyInterestRate.rayMul(scrAmount.wadToRay())).rayDiv(_scr.wadToRay()); } emit SCRLocked(policyInterestRate, scrAmount); _updateTokenInterestRate(); } function unlockScr(uint256 policyInterestRate, uint256 scrAmount) external override onlyPolicyPool { require(scrAmount <= _scr, "Current SCR less than the amount you want to unlock"); _updateCurrentScale(); if (_scr == scrAmount) { _scr = 0; _scrInterestRate = 0; } else { uint256 origScr = _scr.wadToRay(); _scr -= scrAmount; _scrInterestRate = (_scrInterestRate.rayMul(origScr) - policyInterestRate.rayMul(scrAmount.wadToRay())).rayDiv(_scr.wadToRay()); } emit SCRUnlocked(policyInterestRate, scrAmount); _updateTokenInterestRate(); } function _discreteChange(uint256 amount, bool positive) internal { uint256 newTotalSupply = positive ? (totalSupply() + amount) : (totalSupply() - amount); _scaleFactor = newTotalSupply.wadToRay().rayDiv(_totalSupply.wadToRay()); require(_scaleFactor >= MIN_SCALE, "Scale too small, can lead to rounding errors"); _updateTokenInterestRate(); } function discreteEarning(uint256 amount, bool positive) external override onlyPolicyPool { _updateCurrentScale(); _discreteChange(amount, positive); } function assetEarnings(uint256 amount, bool positive) external override onlyAssetManager { _updateCurrentScale(); _discreteChange(amount, positive); } function deposit(address provider, uint256 amount) external override onlyPolicyPool whenNotPaused returns (uint256) { require( address(policyPool().config().lpWhitelist()) == address(0) || policyPool().config().lpWhitelist().acceptsDeposit(this, provider, amount), "Liquidity Provider not whitelisted" ); _updateCurrentScale(); _mint(provider, amount); _updateTokenInterestRate(); return balanceOf(provider); } function totalWithdrawable() public view virtual override returns (uint256) { uint256 locked = _scr .wadToRay() .rayMul(WadRayMath.ray() + _scrInterestRate) .rayMul(_liquidityRequirement) .rayToWad(); uint256 totalSupply_ = totalSupply(); if (totalSupply_ >= locked) return totalSupply_ - locked; else return 0; } function withdraw(address provider, uint256 amount) external override onlyPolicyPool whenNotPaused returns (uint256) { _updateCurrentScale(); uint256 balance = balanceOf(provider); if (balance == 0) return 0; if (amount > balance) amount = balance; uint256 withdrawable = totalWithdrawable(); if (amount > withdrawable) amount = withdrawable; if (amount == 0) return 0; _burn(provider, amount); _updateTokenInterestRate(); return amount; } function accepts(address riskModule, uint40 policyExpiration) public view virtual override returns (bool) { if (paused()) return false; if (_acceptAllRMs == _acceptExceptions[riskModule]) { // all accepted except this one or all rejected and this one is not an exception return false; } return policyExpiration < (uint40(block.timestamp) + _expirationPeriod); } function _updatePoolLoanScale() internal { if (uint40(block.timestamp) == _poolLoanLastUpdate) return; _poolLoanScale = _getPoolLoanScale(); _poolLoanLastUpdate = uint40(block.timestamp); } function _maxNegativeAdjustment() internal view returns (uint256) { uint256 ts = totalSupply(); uint256 minTs = _totalSupply.wadToRay().rayMul(MIN_SCALE * 10).rayToWad(); if (ts > minTs) return ts - minTs; else return 0; } function lendToPool(uint256 amount, bool fromOcean) external override onlyPolicyPool returns (uint256) { if (fromOcean && amount > ocean()) amount = ocean(); if (!fromOcean && amount > totalSupply()) amount = totalSupply(); if (amount > _maxNegativeAdjustment()) { amount = _maxNegativeAdjustment(); if (amount == 0) return amount; } if (_poolLoan == 0) { _poolLoan = amount; _poolLoanScale = WadRayMath.ray(); _poolLoanLastUpdate = uint40(block.timestamp); } else { _updatePoolLoanScale(); _poolLoan += amount.wadToRay().rayDiv(_poolLoanScale).rayToWad(); } _updateCurrentScale(); // shouldn't do anything because lendToPool is after unlock_scr but doing anyway _discreteChange(amount, false); emit PoolLoan(amount); if (!fromOcean && _scr > totalSupply()) { // Notify insolvency_hook - Insuficient solvency IInsolvencyHook hook = _policyPool.config().insolvencyHook(); if (address(hook) != address(0)) { hook.insolventEToken(this, _scr - totalSupply()); } } return amount; } function repayPoolLoan(uint256 amount) external override onlyPolicyPool { _updatePoolLoanScale(); _poolLoan = (getPoolLoan() - amount).wadToRay().rayDiv(_poolLoanScale).rayToWad(); _updateCurrentScale(); // shouldn't do anything because lendToPool is after unlock_scr but doing anyway _discreteChange(amount, true); emit PoolLoanRepaid(amount); } function _getPoolLoanScale() internal view returns (uint256) { if (uint40(block.timestamp) <= _poolLoanLastUpdate) return _poolLoanScale; uint256 timeDifference = block.timestamp - _poolLoanLastUpdate; return _poolLoanScale.rayMul( ((_poolLoanInterestRate * timeDifference) / SECONDS_PER_YEAR) + WadRayMath.ray() ); } function getPoolLoan() public view virtual override returns (uint256) { if (_poolLoan == 0) return 0; return _poolLoan.wadToRay().rayMul(_getPoolLoanScale()).rayToWad(); } function poolLoanInterestRate() public view returns (uint256) { return _poolLoanInterestRate; } function acceptAllRMs() public view returns (bool) { return _acceptAllRMs; } function isAcceptException(address riskModule) public view returns (bool) { return _acceptExceptions[riskModule]; } function setPoolLoanInterestRate(uint256 newRate) external onlyPoolRole2(LEVEL2_ROLE, LEVEL3_ROLE) validateParamsAfterChange { bool tweak = !hasPoolRole(LEVEL2_ROLE); require( !tweak || _isTweakRay(_poolLoanInterestRate, newRate, 3e26), "Tweak exceeded: poolLoanInterestRate tweaks only up to 30%" ); _updatePoolLoanScale(); _poolLoanInterestRate = newRate; _parameterChanged(IPolicyPoolConfig.GovernanceActions.setPoolLoanInterestRate, newRate, tweak); } function setLiquidityRequirement(uint256 newRate) external onlyPoolRole2(LEVEL2_ROLE, LEVEL3_ROLE) validateParamsAfterChange { bool tweak = !hasPoolRole(LEVEL2_ROLE); require( !tweak || _isTweakRay(_liquidityRequirement, newRate, 1e26), "Tweak exceeded: liquidityRequirement tweaks only up to 10%" ); _liquidityRequirement = newRate; _parameterChanged(IPolicyPoolConfig.GovernanceActions.setLiquidityRequirement, newRate, tweak); } function setMaxUtilizationRate(uint256 newRate) external onlyPoolRole2(LEVEL2_ROLE, LEVEL3_ROLE) validateParamsAfterChange { bool tweak = !hasPoolRole(LEVEL2_ROLE); require( !tweak || _isTweakRay(_maxUtilizationRate, newRate, 3e26), "Tweak exceeded: maxUtilizationRate tweaks only up to 30%" ); _maxUtilizationRate = newRate; _parameterChanged(IPolicyPoolConfig.GovernanceActions.setMaxUtilizationRate, newRate, tweak); } function setAcceptAllRMs(bool acceptAllRMs_) external onlyPoolRole(LEVEL2_ROLE) validateParamsAfterChange { _acceptAllRMs = acceptAllRMs_; _parameterChanged( IPolicyPoolConfig.GovernanceActions.setAcceptAllRMs, acceptAllRMs_ ? 1 : 0, false ); } function setAcceptException(address riskModule, bool isException) external onlyPoolRole(LEVEL2_ROLE) validateParamsAfterChange { _acceptExceptions[riskModule] = isException; uint256 value = uint160(riskModule); if (!isException) value |= (1 << 255); // if changed to NOT exception activate first bit _parameterChanged(IPolicyPoolConfig.GovernanceActions.setAcceptException, value, false); } function getInvestable() public view virtual override returns (uint256) { return _scr + ocean() + getPoolLoan(); } }
See {IERC20-balanceOf}./
function balanceOf(address account) public view virtual override returns (uint256) { uint256 principalBalance = _balances[account]; if (principalBalance == 0) return 0; return principalBalance.wadToRay().rayMul(_calculateCurrentScale()).rayToWad(); }
5,490,950
./full_match/43114/0x6B003F9E01375db17171FA0bC1Dfc2d9c1EC27AA/sources/contracts/MasterChefV2.sol
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 oreReward = multiplier.mul(orePerBlock).mul(pool.allocPoint).div(totalAllocPoint); OToken(Ore).mint(address(this), oreReward); pool.accOrePerShare = pool.accOrePerShare.add(oreReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
4,559,519
//SPDX-License-Identifier: MIT pragma solidity >=0.6.0 < 8.3.0; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; //import "https://raw.githubusercontent.com/smartcontractkit/chainlink/master/evm-contracts/src/v0.6/VRFConsumerBase.sol"; contract CoinToss is VRFConsumerBase{ address public house; //Chainlink vrf stuff bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; /**Constructor must inherit VRFconsumerBase Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 */ constructor() VRFConsumerBase( 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9, // VRF Coordinator 0xa36085F69e2889c224210F603D836748e7dC0088 // LINK Token ) public payable{ house = msg.sender; keyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4; fee = 0.1 * 10 ** 18; // 0.1 LINK (fixed on kovan) } //mapping of wagers, deposit status, and their selection mapping(address => uint) public ethBalanceOf; mapping(address => bool) public isDeposited; mapping(address => bool) public selectionOf; mapping(address => bool) public inProg; mapping(address => uint) public wagerOf; mapping(address => bytes32) public requestIdOf; mapping(bytes32 => bool) public resultOfRequest; event Deposit(address indexed user, uint ethAmount); // ADAPTED FROM https://docs.chain.link/docs/get-a-random-number event RequestRandomness(address indexed user, bool selection, bytes32 requestId); event RequestRandomnessFulfilled(uint requestId, bool outcome); event WithdrawRequest(address user, uint amount); event RequestNotRandom(address user, uint amount, bool selection); function notRandom() public returns (bytes32 requestId){ //test function for logic without having to use a testnet requestId = blockhash(block.number); notRandomCallback(requestId); return (requestId); } function notRandomCallback(bytes32 requestId) public { uint notRandomResult = block.number.mod(2); if (notRandomResult == 0){ resultOfRequest[requestId] = true ; } else { resultOfRequest[requestId] = false; } } function getRandomNumber() public returns (bytes32 requestId) { // require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); //use hash the blockhash of the current block number as a seed uint256 seed = uint256(keccak256(abi.encode(blockhash(block.number)))); return requestRandomness(keyHash, fee, seed); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness.mod(2); if (randomResult == 0){ resultOfRequest[requestId] = true ; } else { resultOfRequest[requestId] = false; } // emit RequestRandomnessFulfilled(requestId, randomResult); } function flipCoin(uint amount, bool selection) payable public returns(uint, uint) { //require(isDeposited[msg.sender] == false, 'Game in progress'); // require(msg.value >= 1e16, 'Wagers should be greater than 0.01 ETH'); uint pre = ethBalanceOf[msg.sender]; ethBalanceOf[msg.sender] = ethBalanceOf[msg.sender] - amount; uint post = ethBalanceOf[msg.sender]; wagerOf[msg.sender] = amount; selectionOf[msg.sender] = selection; inProg[msg.sender] = true; //requestIdOf[msg.sender] = getRandomNumber(); requestIdOf[msg.sender] = notRandom(); emit RequestNotRandom(msg.sender, amount, selection); return(pre, post); } function deposit(uint amount) payable public{ // require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); //store balance ethBalanceOf[msg.sender] = ethBalanceOf[msg.sender] + amount; //store choice; true = heads, false = tails //selectionOf[msg.sender] = selectionOf[msg.sender] + selection; //flag wager as deposited and amount //isDeposited[msg.sender] = true; emit Deposit(msg.sender, amount); //use hash the blockhash of the current block number as a seed uint256 seed = uint256(keccak256(abi.encode(blockhash(block.number)))); // emit RequestRandomness(msg.sender, selection); } function balanceOf(address user) public view returns(uint balance){ balance = ethBalanceOf[user]; return balance; } function payout() payable public returns (uint){ uint winnings = 0; if (inProg[msg.sender] == true) { bytes32 request = requestIdOf[msg.sender]; if (resultOfRequest[request] == selectionOf[msg.sender]){ winnings = wagerOf[msg.sender] * 2; } } //mmight only need that one for when we actually withdraw //payable(msg.sender).transfer(winnings); ethBalanceOf[msg.sender] = ethBalanceOf[msg.sender] + winnings; inProg[msg.sender] = false; wagerOf[msg.sender] = 0; requestIdOf[msg.sender] = 0; return(winnings); } function withdraw(uint amount) payable public { if (amount <= ethBalanceOf[msg.sender]){ payable(msg.sender).transfer(amount); ethBalanceOf[msg.sender] = ethBalanceOf[msg.sender] - amount; emit WithdrawRequest(msg.sender, amount); } } }
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");use hash the blockhash of the current block number as a seed
function getRandomNumber() public returns (bytes32 requestId) { uint256 seed = uint256(keccak256(abi.encode(blockhash(block.number)))); return requestRandomness(keyHash, fee, seed); }
7,312,464
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function getOwner() external view returns (address); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); } /* * @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() {} function _msgSender() internal view returns (address) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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); } } } } /** * @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 { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @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; } function increment(uint256 a) internal pure returns (uint256) { uint256 b = a + 1; require(b >= a, "SafeMath: addition overflow"); return b; } function decrement(uint256 a) internal pure returns (uint256) { require(1 <= a, "SafeMath: subtraction overflow"); uint256 b = a - 1; return 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 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 Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } } /** * @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() { 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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ReedBricks is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; //event Received(address sender, uint256 value); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) private _allowances; // base controller of the token contract address public controller = 0x63841FFdDfB1e275a9eC163e0332962E27fD5AAb; address public feecollector = 0x63841FFdDfB1e275a9eC163e0332962E27fD5AAb; uint8 private _decimals = 18; uint256 private _totalSupply = 1 * 10**9 * _decimals; string private _name = "ReedBricks"; string private _symbol = "REED"; //Authorised Admins// mapping(address => bool) private isAdmin; // set of investors, for locking funding struct Investor { address account; uint256 amount; uint256 locked; bool exists; } event InvestorAdded( uint256 indexed id, address _account, uint256 amount, uint256 locked ); event InvestorRemoved(uint256 indexed id); Investor[] investors; uint256 private investorCount = 0; uint256 private _totalFee = 0; uint256 private _taxFee = 5; //5%// uint256 private immutable _mintcap = _totalSupply; uint256 private immutable _burncap = _totalSupply.div(2); constructor() { //_balances[msg.sender] = _totalSupply; _mint(msg.sender, _totalSupply); emit Transfer(address(0), msg.sender, _totalSupply); } // accept incoming ETH receive() external payable { // React to receiving ether //emit Received(msg.sender, msg.value); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(isAdmin[msg.sender], "Ownable: caller is not an admin"); _; } /** * @dev Returns the mint cap on the token's total supply. */ function mintCap() public view virtual returns (uint256) { return _mintcap; } /** * @dev Returns the burn cap on the token's total supply. */ function burnCap() public view virtual returns (uint256) { return _burncap; } /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address) { return owner(); } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view override returns (uint256) { return _totalSupply; } function makeAdmin(address account) public onlyOwner returns (bool) { isAdmin[account] = true; return true; } function removeAdmin(address account) public onlyOwner returns (bool) { isAdmin[account] = false; return true; } /** * @dev Returns the total investor count. */ function countInvestors() external view returns (uint8) { return _decimals; } function removeInvestor(uint256 id) public onlyAdmin returns (bool) { _removeInvestor(id); return true; } function _removeInvestor(uint256 _id) internal { require(investors[_id].exists, "Investor does not exist."); delete investors[_id]; investorCount.decrement(); emit InvestorRemoved(_id); } function addInvestor( address investor, uint256 amount, uint256 _days ) public onlyAdmin returns (bool) { _addInvestor(investor, amount, _days); return true; } function _addInvestor( address _investor, uint256 _amount, uint256 _days ) internal { uint256 id = investorCount.increment(); uint256 time_lock = createEscrow(_days); Investor memory investor = Investor( _investor, _amount, time_lock, true ); investors.push(investor); emit InvestorAdded(id, _investor, _amount, _days); } function createEscrow(uint256 _days) internal view onlyOwner returns (uint256) { uint256 expirationDate = block.timestamp + _days * 1 days; return expirationDate; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external 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 {IERC20}; * * 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 ) external override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "IERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "IERC20: decreased allowance below zero" ) ); return true; } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. */ function burn(uint256 amount) public onlyOwner returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "IERC20: transfer from the zero address"); require( recipient != address(0), "IERC20: transfer to the zero address" ); uint256 taxtAmount = amount.mul(_taxFee).div(100); uint256 newAmount = amount.sub(taxtAmount); _balances[sender] = _balances[sender].sub( newAmount, "IERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(newAmount); emit Transfer(sender, recipient, newAmount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "IERC20: burn from the zero address"); require( _totalSupply - amount <= burnCap(), "ERC20Capped: burnable cap exceeded" ); _balances[account] = _balances[account].sub( amount, "IERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "IERC20: approve from the zero address"); require(spender != address(0), "IERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, _msgSender(), _allowances[account][_msgSender()].sub( amount, "IERC20: burn amount exceeds allowance" ) ); } function mint(address to, uint256 amount) external onlyOwner returns (bool) { _mint(to, amount); return true; } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require( _totalSupply + amount <= mintCap(), "ERC20Capped: cap exceeded" ); _totalSupply += amount; balanceOf[account] += amount; emit Transfer(address(0), account, amount); } }
Creates `amount` tokens and assigns them to `account`, increasing the total supply. Emits a {Transfer} event with `from` set to the zero address. Requirements - `to` cannot be the zero address./
function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); require( _totalSupply + amount <= mintCap(), "ERC20Capped: cap exceeded" ); _totalSupply += amount; balanceOf[account] += amount; emit Transfer(address(0), account, amount); }
2,538,203
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./RoyalNFT.sol"; /** * @title Althea NFT * * @notice Alethea NFT is an ERC721 token used as a target NFT for iNFT protocol * * @dev Alethea NFT is a Tiny ERC721, it supports minting and burning, * its token ID space is limited to 32 bits */ contract AletheaNFT is RoyalNFT { /** * @inheritdoc TinyERC721 */ uint256 public constant override TOKEN_UID = 0x275ee64af649fe998ccbaec4f443dc216eef3bab6f11080eeeedfbdd303c59a6; /** * @dev Constructs/deploys AI Personality instance * with the name and symbol defined during the deployment */ constructor(string memory _name, string memory _symbol) RoyalNFT(_name, _symbol) {} } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/EIP2981Spec.sol"; import "./TinyERC721.sol"; /** * @title Royal NFT * * @dev Supports EIP-2981 royalties on NFT secondary sales * * @dev Supports OpenSea contract metadata royalties * * @dev Introduces "owner" to support OpenSea collections */ abstract contract RoyalNFT is EIP2981, TinyERC721 { /** * @dev OpenSea expects NFTs to be "Ownable", that is having an "owner", * we introduce a fake "owner" here with no authority */ address public owner; /** * @dev Constructs/deploys ERC721 with EIP-2981 instance with the name and symbol specified * * @param _name name of the token to be accessible as `name()`, * ERC-20 compatible descriptive name for a collection of NFTs in this contract * @param _symbol token symbol to be accessible as `symbol()`, * ERC-20 compatible descriptive name for a collection of NFTs in this contract */ constructor(string memory _name, string memory _symbol) TinyERC721(_name, _symbol) { // initialize the "owner" as a deployer account owner = msg.sender; } /** * @dev Fired in setContractURI() * * @param _by an address which executed update * @param _oldVal old contractURI value * @param _newVal new contractURI value */ event ContractURIUpdated(address indexed _by, string _oldVal, string _newVal); /** * @dev Fired in setRoyaltyInfo() * * @param _by an address which executed update * @param _oldReceiver old royaltyReceiver value * @param _newReceiver new royaltyReceiver value * @param _oldPercentage old royaltyPercentage value * @param _newPercentage new royaltyPercentage value */ event RoyaltyInfoUpdated( address indexed _by, address indexed _oldReceiver, address indexed _newReceiver, uint16 _oldPercentage, uint16 _newPercentage ); /** * @dev Fired in setOwner() * * @param _by an address which set the new "owner" * @param _oldVal previous "owner" address * @param _newVal new "owner" address */ event OwnerUpdated(address indexed _by, address indexed _oldVal, address indexed _newVal); /** * @notice Royalty manager is responsible for managing the EIP2981 royalty info * * @dev Role ROLE_ROYALTY_MANAGER allows updating the royalty information * (executing `setRoyaltyInfo` function) */ uint32 public constant ROLE_ROYALTY_MANAGER = 0x0020_0000; /** * @notice Owner manager is responsible for setting/updating an "owner" field * * @dev Role ROLE_OWNER_MANAGER allows updating the "owner" field * (executing `setOwner` function) */ uint32 public constant ROLE_OWNER_MANAGER = 0x0040_0000; /** * @notice Address to receive EIP-2981 royalties from secondary sales * see https://eips.ethereum.org/EIPS/eip-2981 */ address public royaltyReceiver = address(0x379e2119f6e0D6088537da82968e2a7ea178dDcF); /** * @notice Percentage of token sale price to be used for EIP-2981 royalties from secondary sales * see https://eips.ethereum.org/EIPS/eip-2981 * * @dev Has 2 decimal precision. E.g. a value of 500 would result in a 5% royalty fee */ uint16 public royaltyPercentage = 750; /** * @notice Contract level metadata to define collection name, description, and royalty fees. * see https://docs.opensea.io/docs/contract-level-metadata * * @dev Should be overwritten by inheriting contracts. By default only includes royalty information */ string public contractURI = "https://gateway.pinata.cloud/ipfs/QmU92w8iKpcaabCoyHtMg7iivWGqW2gW1hgARDtqCmJUWv"; /** * @dev Restricted access function which updates the contract uri * * @dev Requires executor to have ROLE_URI_MANAGER permission * * @param _contractURI new contract URI to set */ function setContractURI(string memory _contractURI) public { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // emit an event first - to log both old and new values emit ContractURIUpdated(msg.sender, contractURI, _contractURI); // update the contract URI contractURI = _contractURI; } /** * @notice EIP-2981 function to calculate royalties for sales in secondary marketplaces. * see https://eips.ethereum.org/EIPS/eip-2981 * * @param _tokenId the token id to calculate royalty info for * @param _salePrice the price (in any unit, .e.g wei, ERC20 token, et.c.) of the token to be sold * * @return receiver the royalty receiver * @return royaltyAmount royalty amount in the same unit as _salePrice */ function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view override returns ( address receiver, uint256 royaltyAmount ) { // simply calculate the values and return the result return (royaltyReceiver, _salePrice * royaltyPercentage / 100_00); } /** * @dev Restricted access function which updates the royalty info * * @dev Requires executor to have ROLE_ROYALTY_MANAGER permission * * @param _royaltyReceiver new royalty receiver to set * @param _royaltyPercentage new royalty percentage to set */ function setRoyaltyInfo( address _royaltyReceiver, uint16 _royaltyPercentage ) public { // verify the access permission require(isSenderInRole(ROLE_ROYALTY_MANAGER), "access denied"); // verify royalty percentage is zero if receiver is also zero require(_royaltyReceiver != address(0) || _royaltyPercentage == 0, "invalid receiver"); // emit an event first - to log both old and new values emit RoyaltyInfoUpdated( msg.sender, royaltyReceiver, _royaltyReceiver, royaltyPercentage, _royaltyPercentage ); // update the values royaltyReceiver = _royaltyReceiver; royaltyPercentage = _royaltyPercentage; } /** * @notice Checks if the address supplied is an "owner" of the smart contract * Note: an "owner" doesn't have any authority on the smart contract and is "nominal" * * @return true if the caller is the current owner. */ function isOwner(address _addr) public view returns(bool) { // just evaluate and return the result return _addr == owner; } /** * @dev Restricted access function to set smart contract "owner" * Note: an "owner" set doesn't have any authority, and cannot even update "owner" * * @dev Requires executor to have ROLE_OWNER_MANAGER permission * * @param _owner new "owner" of the smart contract */ function transferOwnership(address _owner) public { // verify the access permission require(isSenderInRole(ROLE_OWNER_MANAGER), "access denied"); // emit an event first - to log both old and new values emit OwnerUpdated(msg.sender, owner, _owner); // update "owner" owner = _owner; } /** * @inheritdoc ERC165 */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, TinyERC721) returns (bool) { // construct the interface support from EIP-2981 and super interfaces return interfaceId == type(EIP2981).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ERC165Spec.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface EIP2981 is ERC165 { /// ERC165 bytes to add to interface array - set in parent contract /// implementing this standard /// /// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a /// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /// _registerInterface(_INTERFACE_ID_ERC2981); /// @notice Called with the sale price to determine how much royalty // is owed and to whom. /// @param _tokenId - the NFT asset queried for royalty information /// @param _salePrice - the sale price of the NFT asset specified by _tokenId /// @return receiver - address of who should be sent the royalty payment /// @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/ERC721Spec.sol"; import "../interfaces/AletheaERC721Spec.sol"; import "../lib/AddressUtils.sol"; import "../lib/ArrayUtils.sol"; import "../lib/StringUtils.sol"; import "../lib/ECDSA.sol"; import "../utils/AccessControl.sol"; /** * @title Tiny ERC721 * * @notice Tiny ERC721 defines an NFT with a very small (up to 32 bits) ID space. * ERC721 enumeration support requires additional writes to the storage: * - when transferring a token in order to update the NFT collections of * the previous and next owners, * - when minting/burning a token in order to update global NFT collection * * @notice Reducing NFT ID space to 32 bits allows * - to eliminate the need to have and to write to two additional storage mappings * (also achievable with the 48 bits ID space) * - for batch minting optimization by writing 8 tokens instead of 5 at once into * global/local collections * * @notice This smart contract is designed to be inherited by concrete implementations, * which are expected to define token metadata, auxiliary functions to access the metadata, * and explicitly define token minting interface, which should be built on top * of current smart contract internal interface * * @notice Fully ERC721-compatible with all optional interfaces implemented (metadata, enumeration), * see https://eips.ethereum.org/EIPS/eip-721 * * @dev ERC721: contract has passed adopted OpenZeppelin ERC721 tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC721/ERC721.behavior.js * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC721/extensions/ERC721URIStorage.test.js * * @dev A note on token URI: there are major differences on how token URI behaves comparing to Zeppelin impl: * 1. A token URI can be set for non-existing token for pre-allocation purposes, * still the URI will be deleted once token is burnt * 2. If token URI is set, base URI has no affect on the token URI, the two are not concatenated, * base URI is used to construct the token URI only if the latter was not explicitly set * * @dev Supports EIP-712 powered permits - permit() - approve() with signature. * Supports EIP-712 powered operator permits - permitForAll() - setApprovalForAll() with signature. * * @dev EIP712 Domain: * name: AliERC721v1 * version: not in use, omitted (name already contains version) * chainId: EIP-155 chain id * verifyingContract: deployed contract address * salt: permitNonces[owner], where owner is an address which allows operation on their tokens * * @dev Permit type: * owner: address * operator: address * tokenId: uint256 * nonce: uint256 * deadline: uint256 * * @dev Permit typeHash: * keccak256("Permit(address owner,address operator,uint256 tokenId,uint256 nonce,uint256 deadline)") * * @dev PermitForAll type: * owner: address * operator: address * approved: bool * nonce: uint256 * deadline: uint256 * * @dev PermitForAll typeHash: * keccak256("PermitForAll(address owner,address operator,bool approved,uint256 nonce,uint256 deadline)") * * @dev See https://eips.ethereum.org/EIPS/eip-712 * @dev See usage examples in tests: erc721_permits.js */ abstract contract TinyERC721 is ERC721Enumerable, ERC721Metadata, WithBaseURI, MintableERC721, BurnableERC721, AccessControl { // enable push32 optimization for uint32[] using ArrayUtils for uint32[]; /** * @dev Smart contract unique identifier, a random number * * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * * @dev Generated using https://www.random.org/bytes/ * @dev Example value: 0xdbdd2b4ff38a8516da0b8e7ae93288b5e2fed0c92fb051cee90ccf4e4ec9736e */ function TOKEN_UID() external view virtual returns(uint256); /** * @notice ERC-20 compatible descriptive name for a collection of NFTs in this contract * * @inheritdoc ERC721Metadata */ string public override name; /** * @notice ERC-20 compatible abbreviated name for a collection of NFTs in this contract * * @inheritdoc ERC721Metadata */ string public override symbol; /** * @notice Current implementation includes a function `decimals` that returns uint8(0) * to be more compatible with ERC-20 * * @dev ERC20 compliant token decimals is equal to zero since ERC721 token is non-fungible * and therefore non-divisible */ uint8 public constant decimals = 0; /** * @notice Ownership information for all the tokens in existence * * @dev Maps `Token ID => Token ID Global Index | Token ID Local Index | Token Owner Address`, where * - Token ID Global Index denotes Token ID index in the array of all the tokens, * - Token ID Local Index denotes Token ID index in the array of all the tokens owned by the owner, * - Token ID indexes are 32 bits long, * - `|` denotes bitwise concatenation of the values * @dev Token Owner Address for a given Token ID is lower 160 bits of the mapping value */ mapping(uint256 => uint256) internal tokens; /** * @notice Enumerated collections of the tokens owned by particular owners * * @dev We call these collections "Local" token collections * * @dev Maps `Token Owner Address => Owned Token IDs Array` * * @dev Token owner balance is the length of their token collection: * `balanceOf(owner) = collections[owner].length` */ mapping(address => uint32[]) internal collections; /** * @notice An array of all the tokens in existence * * @dev We call this collection "Global" token collection * * @dev Array with all Token IDs, used for enumeration * * @dev Total token supply `tokenSupply` is the length of this collection: * `totalSupply() = allTokens.length` */ uint32[] internal allTokens; /** * @notice Addresses approved by token owners to transfer their tokens * * @dev `Maps Token ID => Approved Address`, where * Approved Address is an address allowed transfer ownership for the token * defined by Token ID */ mapping(uint256 => address) internal approvals; /** * @notice Addresses approved by token owners to transfer all their tokens * * @dev Maps `Token Owner Address => Operator Address => Approval State` - true/false (approved/not), where * - Token Owner Address is any address which may own tokens or not, * - Operator Address is any other address which may own tokens or not, * - Approval State is a flag indicating if Operator Address is allowed to * transfer tokens owned by Token Owner Address o their behalf */ mapping(address => mapping(address => bool)) internal approvedOperators; /** * @dev A record of nonces for signing/validating signatures in EIP-712 based * `permit` and `permitForAll` functions * * @dev Each time the nonce is used, it is increased by one, meaning reordering * of the EIP-712 transactions is not possible * * @dev Inspired by EIP-2612 extension for ERC20 token standard * * @dev Maps token owner address => token owner nonce */ mapping(address => uint256) public permitNonces; /** * @dev Base URI is used 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 * * @dev If token URI is set with `setTokenURI()` it will be returned as is via `tokenURI()` */ string public override baseURI = ""; /** * @dev Optional mapping for token URIs to be returned as is when `tokenURI()` * is called; if mapping doesn't exist for token, the URI is constructed * as `base URI + token ID`, where plus (+) denotes string concatenation */ mapping(uint256 => string) internal _tokenURIs; /** * @dev 32 bit token ID space is optimal for batch minting in batches of size 8 * 8 * 32 = 256 - single storage slot in global/local collection(s) */ uint8 public constant BATCH_SIZE_MULTIPLIER = 8; /** * @notice Enables ERC721 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transferFrom()` function to succeed when executed by token owner */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC721 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed whe executed by approved operator * @dev Token owner must call `approve()` or `setApprovalForAll()` * first to authorize the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @notice Enables token owners to burn their own tokens * * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners * * @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables approvals on behalf (permits via an EIP712 signature) * @dev Feature FEATURE_PERMITS must be enabled in order for * `permit()` function to succeed */ uint32 public constant FEATURE_PERMITS = 0x0000_0200; /** * @notice Enables operator approvals on behalf (permits for all via an EIP712 signature) * @dev Feature FEATURE_OPERATOR_PERMITS must be enabled in order for * `permitForAll()` function to succeed */ uint32 public constant FEATURE_OPERATOR_PERMITS = 0x0000_0400; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice URI manager is responsible for managing base URI * part of the token URI ERC721Metadata interface * * @dev Role ROLE_URI_MANAGER allows updating the base URI * (executing `setBaseURI` function) */ uint32 public constant ROLE_URI_MANAGER = 0x0010_0000; /** * @notice EIP-712 contract's domain typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash * * @dev Note: we do not include version into the domain typehash/separator, * it is implied version is concatenated to the name field, like "AliERC721v1" */ // keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)") bytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866; /** * @notice EIP-712 contract's domain separator, * see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator */ bytes32 public immutable DOMAIN_SEPARATOR; /** * @notice EIP-712 permit (EIP-2612) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("Permit(address owner,address operator,uint256 tokenId,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0xee2282d7affd5a432b221a559e429129347b0c19a3f102179a5fb1859eef3d29; /** * @notice EIP-712 permitForAll (EIP-2612) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("PermitForAll(address owner,address operator,bool approved,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_FOR_ALL_TYPEHASH = 0x47ab88482c90e4bb94b82a947ae78fa91fb25de1469ab491f4c15b9a0a2677ee; /** * @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 Fired in setTokenURI() * * @param _by an address which executed update * @param _tokenId token ID which URI was updated * @param _oldVal old _baseURI value * @param _newVal new _baseURI value */ event TokenURIUpdated(address indexed _by, uint256 _tokenId, string _oldVal, string _newVal); /** * @dev Constructs/deploys ERC721 instance with the name and symbol specified * * @param _name name of the token to be accessible as `name()`, * ERC-20 compatible descriptive name for a collection of NFTs in this contract * @param _symbol token symbol to be accessible as `symbol()`, * ERC-20 compatible descriptive name for a collection of NFTs in this contract */ constructor(string memory _name, string memory _symbol) { // set the name name = _name; // set the symbol symbol = _symbol; // build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator // note: we specify contract version in its name DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AliERC721v1")), block.chainid, address(this))); } /** * @dev Verifies if token is transferable (i.e. can change ownership, allowed to be transferred); * The default behaviour is to always allow transfer if token exists * * @dev Implementations may modify the default behaviour based on token metadata * if required * * @param _tokenId ID of the token to check if it's transferable * @return true if token is transferable, false otherwise */ function isTransferable(uint256 _tokenId) public view virtual returns(bool) { // validate token existence require(exists(_tokenId), "token doesn't exist"); // generic implementation returns true if token exists return true; } /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * * @inheritdoc MintableERC721 * * @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) public override view returns(bool) { // read ownership information and return a check if it's not zero (set) return tokens[_tokenId] != 0; } /** * @inheritdoc ERC165 */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { // construct the interface support from required and optional ERC721 interfaces return interfaceId == type(ERC165).interfaceId || interfaceId == type(ERC721).interfaceId || interfaceId == type(ERC721Metadata).interfaceId || interfaceId == type(ERC721Enumerable).interfaceId || interfaceId == type(MintableERC721).interfaceId || interfaceId == type(BurnableERC721).interfaceId; } // ===== Start: ERC721 Metadata ===== /** * @dev Restricted access function which updates base URI used to construct * ERC721Metadata.tokenURI * * @dev Requires executor to have ROLE_URI_MANAGER permission * * @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; } /** * @dev Returns token URI if it was previously set with `setTokenURI`, * otherwise constructs it as base URI + token ID * * @inheritdoc ERC721Metadata */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { // verify token exists require(exists(_tokenId), "token doesn't exist"); // read the token URI for the token specified string memory _tokenURI = _tokenURIs[_tokenId]; // if token URI is set if(bytes(_tokenURI).length > 0) { // just return it return _tokenURI; } // if base URI is not set if(bytes(baseURI).length == 0) { // return an empty string return ""; } // otherwise concatenate base URI + token ID return StringUtils.concat(baseURI, StringUtils.itoa(_tokenId, 10)); } /** * @dev Sets the token URI for the token defined by its ID * * @param _tokenId an ID of the token to set URI for * @param _tokenURI token URI to set */ function setTokenURI(uint256 _tokenId, string memory _tokenURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // we do not verify token existence: we want to be able to // preallocate token URIs before tokens are actually minted // emit an event first - to log both old and new values emit TokenURIUpdated(msg.sender, _tokenId, _tokenURIs[_tokenId], _tokenURI); // and update token URI _tokenURIs[_tokenId] = _tokenURI; } // ===== End: ERC721 Metadata ===== // ===== Start: ERC721, ERC721Enumerable Getters (view functions) ===== /** * @inheritdoc ERC721 */ function balanceOf(address _owner) public view override returns (uint256) { // check `_owner` address is set require(_owner != address(0), "zero address"); // derive owner balance for the their owned tokens collection // as the length of that collection return collections[_owner].length; } /** * @inheritdoc ERC721 */ function ownerOf(uint256 _tokenId) public view override returns (address) { // derive ownership information of the token from the ownership mapping // by extracting lower 160 bits of the mapping value as an address address owner = address(uint160(tokens[_tokenId])); // verify owner/token exists require(owner != address(0), "token doesn't exist"); // return owner address return owner; } /** * @inheritdoc ERC721Enumerable */ function totalSupply() public view override returns (uint256) { // derive total supply value from the array of all existing tokens // as the length of this array return allTokens.length; } /** * @inheritdoc ERC721Enumerable */ function tokenByIndex(uint256 _index) public view override returns (uint256) { // index out of bounds check require(_index < totalSupply(), "index out of bounds"); // find the token ID requested and return return allTokens[_index]; } /** * @inheritdoc ERC721Enumerable */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view override returns (uint256) { // index out of bounds check require(_index < balanceOf(_owner), "index out of bounds"); // find the token ID requested and return return collections[_owner][_index]; } /** * @inheritdoc ERC721 */ function getApproved(uint256 _tokenId) public view override returns (address) { // verify token specified exists require(exists(_tokenId), "token doesn't exist"); // read the approval value and return return approvals[_tokenId]; } /** * @inheritdoc ERC721 */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool) { // read the approval state value and return return approvedOperators[_owner][_operator]; } // ===== End: ERC721, ERC721Enumerable Getters (view functions) ===== // ===== Start: ERC721 mutative functions (transfers, approvals) ===== /** * @inheritdoc ERC721 */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public override { // delegate call to unsafe transfer on behalf `transferFrom()` transferFrom(_from, _to, _tokenId); // if receiver `_to` is a smart contract if(AddressUtils.isContract(_to)) { // check it supports ERC721 interface - execute onERC721Received() bytes4 response = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); // expected response is ERC721TokenReceiver(_to).onERC721Received.selector // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) require(response == ERC721TokenReceiver(_to).onERC721Received.selector, "invalid onERC721Received response"); } } /** * @inheritdoc ERC721 */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public override { // delegate call to overloaded `safeTransferFrom()`, set data to "" safeTransferFrom(_from, _to, _tokenId, ""); } /** * @inheritdoc ERC721 */ function transferFrom(address _from, address _to, uint256 _tokenId) public override { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_TRANSFERS) || _from != msg.sender && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == msg.sender? "transfers are disabled": "transfers on behalf are disabled"); // validate destination address is set require(_to != address(0), "zero address"); // validate token ownership, which also // validates token existence under the hood require(_from == ownerOf(_tokenId), "access denied"); // verify operator (transaction sender) is either token owner, // or is approved by the token owner to transfer this particular token, // or is approved by the token owner to transfer any of his tokens require(_from == msg.sender || msg.sender == getApproved(_tokenId) || isApprovedForAll(_from, msg.sender), "access denied"); // transfer is not allowed for a locked token require(isTransferable(_tokenId), "locked token"); // if required, move token ownership, // update old and new owner's token collections accordingly: if(_from != _to) { // remove token from old owner's collection (also clears approval) __removeLocal(_tokenId); // add token to the new owner's collection __addLocal(_tokenId, _to); } // even if no real changes are required, approval needs to be erased else { // clear token approval (also emits an Approval event) __clearApproval(_from, _tokenId); } // fire ERC721 transfer event emit Transfer(_from, _to, _tokenId); } /** * @inheritdoc ERC721 */ function approve(address _approved, uint256 _tokenId) public override { // make an internal approve - delegate to `__approve` __approve(msg.sender, _approved, _tokenId); } /** * @dev Powers the meta transaction for `approve` - EIP-712 signed `permit` * * @dev Approves address called `_operator` to transfer token `_tokenId` * on behalf of the `_owner` * * @dev Zero `_operator` address indicates there is no approved address, * and effectively removes an approval for the token specified * * @dev `_owner` must own token `_tokenId` to grant the permission * @dev Throws if `_operator` is a self address (`_owner`), * or if `_tokenId` doesn't exist * * @param _owner owner of the token `_tokenId` to set approval on behalf of * @param _operator an address approved by the token owner * to spend token `_tokenId` on its behalf * @param _tokenId token ID operator `_approved` is allowed to * transfer on behalf of the token owner */ function __approve(address _owner, address _operator, uint256 _tokenId) private { // get token owner address address owner = ownerOf(_tokenId); // approving owner address itself doesn't make sense and is not allowed require(_operator != owner, "self approval"); // only token owner or/and approved operator can set the approval require(_owner == owner || isApprovedForAll(owner, _owner), "access denied"); // update the approval approvals[_tokenId] = _operator; // emit an event emit Approval(owner, _operator, _tokenId); } /** * @inheritdoc ERC721 */ function setApprovalForAll(address _operator, bool _approved) public override { // make an internal approve - delegate to `__approveForAll` __approveForAll(msg.sender, _operator, _approved); } /** * @dev Powers the meta transaction for `setApprovalForAll` - EIP-712 signed `permitForAll` * * @dev Approves address called `_operator` to transfer any tokens * on behalf of the `_owner` * * @dev `_owner` must not necessarily own any tokens to grant the permission * @dev Throws if `_operator` is a self address (`_owner`) * * @param _owner owner of the tokens to set approval on behalf of * @param _operator an address to add to the set of authorized operators, i.e. * an address approved by the token owner to spend tokens on its behalf * @param _approved true if the operator is approved, false to revoke approval */ function __approveForAll(address _owner, address _operator, bool _approved) private { // approving tx sender address itself doesn't make sense and is not allowed require(_operator != _owner, "self approval"); // update the approval approvedOperators[_owner][_operator] = _approved; // emit an event emit ApprovalForAll(_owner, _operator, _approved); } /** * @dev Clears approval for a given token owned by a given owner, * emits an Approval event * * @dev Unsafe: doesn't check the validity of inputs (must be kept private), * assuming the check is done by the caller * - token existence * - token ownership * * @param _owner token owner to be logged into Approved event as is * @param _tokenId token ID to erase approval for and to log into Approved event as is */ function __clearApproval(address _owner, uint256 _tokenId) internal { // clear token approval delete approvals[_tokenId]; // emit an ERC721 Approval event: // "When a Transfer event emits, this also indicates that the approved // address for that NFT (if any) is reset to none." emit Approval(_owner, address(0), _tokenId); } // ===== End: ERC721 mutative functions (transfers, approvals) ===== // ===== Start: Meta-transactions Support ===== /** * @notice Change or reaffirm the approved address for an NFT on behalf * * @dev Executes approve(_operator, _tokenId) on behalf of the token owner * who EIP-712 signed the transaction, i.e. as if transaction sender is the EIP712 signer * * @dev Sets the `_tokenId` as the allowance of `_operator` over `_owner` token, * given `_owner` EIP-712 signed approval * * @dev Emits `Approval` event in the same way as `approve` does * * @dev Requires: * - `_operator` to be non-zero address * - `_exp` to be a timestamp in the future * - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner` * over the EIP712-formatted function arguments. * - the signature to use `_owner` current nonce (see `permitNonces`). * * @dev For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification * * @param _owner owner of the token to set approval on behalf of, * an address which signed the EIP-712 message * @param _operator new approved NFT controller * @param _tokenId token ID to approve * @param _exp signature expiration time (unix timestamp) * @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 permit(address _owner, address _operator, uint256 _tokenId, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify permits are enabled require(isFeatureEnabled(FEATURE_PERMITS), "permits are disabled"); // derive signer of the EIP712 Permit message, and // update the nonce for that particular signer to avoid replay attack!!! ----------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ address signer = __deriveSigner(abi.encode(PERMIT_TYPEHASH, _owner, _operator, _tokenId, permitNonces[_owner]++, _exp), v, r, s); // perform message integrity and security validations require(signer == _owner, "invalid signature"); require(block.timestamp < _exp, "signature expired"); // delegate call to `__approve` - execute the logic required __approve(_owner, _operator, _tokenId); } /** * @notice Enable or disable approval for a third party ("operator") to manage * all of owner's assets - on behalf * * @dev Executes setApprovalForAll(_operator, _approved) on behalf of the owner * who EIP-712 signed the transaction, i.e. as if transaction sender is the EIP712 signer * * @dev Sets the `_operator` as the token operator for `_owner` tokens, * given `_owner` EIP-712 signed approval * * @dev Emits `ApprovalForAll` event in the same way as `setApprovalForAll` does * * @dev Requires: * - `_operator` to be non-zero address * - `_exp` to be a timestamp in the future * - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner` * over the EIP712-formatted function arguments. * - the signature to use `_owner` current nonce (see `permitNonces`). * * @dev For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification * * @param _owner owner of the tokens to set approval on behalf of, * an address which signed the EIP-712 message * @param _operator an address to add to the set of authorized operators, i.e. * an address approved by the token owner to spend tokens on its behalf * @param _approved true if the operator is approved, false to revoke approval * @param _exp signature expiration time (unix timestamp) * @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 permitForAll(address _owner, address _operator, bool _approved, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify permits are enabled require(isFeatureEnabled(FEATURE_OPERATOR_PERMITS), "operator permits are disabled"); // derive signer of the EIP712 PermitForAll message, and // update the nonce for that particular signer to avoid replay attack!!! --------------------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ address signer = __deriveSigner(abi.encode(PERMIT_FOR_ALL_TYPEHASH, _owner, _operator, _approved, permitNonces[_owner]++, _exp), v, r, s); // perform message integrity and security validations require(signer == _owner, "invalid signature"); require(block.timestamp < _exp, "signature expired"); // delegate call to `__approve` - execute the logic required __approveForAll(_owner, _operator, _approved); } /** * @dev Auxiliary function to verify structured EIP712 message signature and derive its signer * * @param abiEncodedTypehash abi.encode of the message typehash together with all its parameters * @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 __deriveSigner(bytes memory abiEncodedTypehash, uint8 v, bytes32 r, bytes32 s) private view returns(address) { // build the EIP-712 hashStruct of the message bytes32 hashStruct = keccak256(abiEncodedTypehash); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); // recover the address which signed the message with v, r, s address signer = ECDSA.recover(digest, v, r, s); // return the signer address derived from the signature return signer; } // ===== End: Meta-transactions Support ===== // ===== Start: mint/burn support ===== /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @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) public override { // delegate to unsafe mint mint(_to, _tokenId); // make it safe: execute `onERC721Received` // if receiver `_to` is a smart contract if(AddressUtils.isContract(_to)) { // check it supports ERC721 interface - execute onERC721Received() bytes4 response = ERC721TokenReceiver(_to).onERC721Received(msg.sender, address(0), _tokenId, _data); // expected response is ERC721TokenReceiver(_to).onERC721Received.selector // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) require(response == ERC721TokenReceiver(_to).onERC721Received.selector, "invalid onERC721Received response"); } } /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) public override { // delegate to `safeMint` with empty data safeMint(_to, _tokenId, ""); } /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @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) public override { // delegate to unsafe mint mintBatch(_to, _tokenId, n); // make it safe: execute `onERC721Received` // if receiver `_to` is a smart contract if(AddressUtils.isContract(_to)) { // onERC721Received: for each token minted for(uint256 i = 0; i < n; i++) { // check it supports ERC721 interface - execute onERC721Received() bytes4 response = ERC721TokenReceiver(_to).onERC721Received(msg.sender, address(0), _tokenId + i, _data); // expected response is ERC721TokenReceiver(_to).onERC721Received.selector // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) require(response == ERC721TokenReceiver(_to).onERC721Received.selector, "invalid onERC721Received response"); } } } /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @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) public override { // delegate to `safeMint` with empty data safeMintBatch(_to, _tokenId, n, ""); } /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) public override { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied"); // verify the inputs // verify destination address is set require(_to != address(0), "zero address"); // verify the token ID is "tiny" (32 bits long at most) require(uint32(_tokenId) == _tokenId, "token ID overflow"); // verify token doesn't yet exist require(!exists(_tokenId), "already minted"); // create token ownership record, // add token to `allTokens` and new owner's collections // add token to both local and global collections (enumerations) __addToken(_tokenId, _to); // fire ERC721 transfer event emit Transfer(address(0), _to, _tokenId); } /** * @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 Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @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) public override { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied"); // verify the inputs // verify destination address is set require(_to != address(0), "zero address"); // verify n is set properly require(n > 1, "n is too small"); // verify the token ID is "tiny" (32 bits long at most) require(uint32(_tokenId) == _tokenId, "token ID overflow"); require(uint32(_tokenId + n - 1) == _tokenId + n - 1, "n-th token ID overflow"); // verification: for each token to be minted for(uint256 i = 0; i < n; i++) { // verify token doesn't yet exist require(!exists(_tokenId + i), "already minted"); } // create token ownership records, // add tokens to `allTokens` and new owner's collections // add tokens to both local and global collections (enumerations) __addTokens(_to, _tokenId, n); // events: for each token minted for(uint256 i = 0; i < n; i++) { // fire ERC721 transfer event emit Transfer(address(0), _to, _tokenId + i); } } /** * @dev Destroys the token with token ID specified * * @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission * or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled * * @dev Can be disabled by the contract creator forever by disabling * FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking * its own roles to burn tokens and to enable burning features * * @param _tokenId ID of the token to burn */ function burn(uint256 _tokenId) public override { // read token owner data // verifies token exists under the hood address _from = ownerOf(_tokenId); // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // verify sender is either token owner, or approved by the token owner to burn tokens require(_from == msg.sender || msg.sender == getApproved(_tokenId) || isApprovedForAll(_from, msg.sender), "access denied"); } // remove token ownership record (also clears approval), // remove token from both local and global collections __removeToken(_tokenId); // delete token URI mapping delete _tokenURIs[_tokenId]; // fire ERC721 transfer event emit Transfer(_from, address(0), _tokenId); } // ===== End: mint/burn support ===== // ----- Start: auxiliary internal/private functions ----- /** * @dev Adds token to the new owner's collection (local), * used internally to transfer existing tokens, to mint new * * @dev Unsafe: doesn't check for data structures consistency * (token existence, token ownership, etc.) * * @dev Must be kept private at all times. Inheriting smart contracts * may be interested in overriding this function. * * @param _tokenId token ID to add * @param _to new owner address to add token to */ function __addLocal(uint256 _tokenId, address _to) internal virtual { // get a reference to the collection where token goes to uint32[] storage destination = collections[_to]; // update local index and ownership, do not change global index tokens[_tokenId] = tokens[_tokenId] // |unused |global | local | ownership information (address) | & 0x00000000FFFFFFFF000000000000000000000000000000000000000000000000 | uint192(destination.length) << 160 | uint160(_to); // push token into the local collection destination.push(uint32(_tokenId)); } /** * @dev Add token to both local and global collections (enumerations), * used internally to mint new tokens * * @dev Unsafe: doesn't check for data structures consistency * (token existence, token ownership, etc.) * * @dev Must be kept private at all times. Inheriting smart contracts * may be interested in overriding this function. * * @param _tokenId token ID to add * @param _to new owner address to add token to */ function __addToken(uint256 _tokenId, address _to) internal virtual { // get a reference to the collection where token goes to uint32[] storage destination = collections[_to]; // update token global and local indexes, ownership tokens[_tokenId] = uint224(allTokens.length) << 192 | uint192(destination.length) << 160 | uint160(_to); // push token into the collection destination.push(uint32(_tokenId)); // push it into the global `allTokens` collection (enumeration) allTokens.push(uint32(_tokenId)); } /** * @dev Add tokens to both local and global collections (enumerations), * used internally to mint new tokens in batches * * @dev Token IDs to be added: [_tokenId, _tokenId + n) * n is expected to be greater or equal 2, but this is not checked * * @dev Unsafe: doesn't check for data structures consistency * (token existence, token ownership, etc.) * * @dev Must be kept private at all times. Inheriting smart contracts * may be interested in overriding this function. * * @param _to new owner address to add token to * @param _tokenId first token ID to add * @param n how many tokens to add, sequentially increasing the _tokenId */ function __addTokens(address _to, uint256 _tokenId, uint256 n) internal virtual { // get a reference to the collection where tokens go to uint32[] storage destination = collections[_to]; // for each token to be added for(uint256 i = 0; i < n; i++) { // update token global and local indexes, ownership tokens[_tokenId + i] = uint224(allTokens.length + i) << 192 | uint192(destination.length + i) << 160 | uint160(_to); } // push tokens into the local collection destination.push32(uint32(_tokenId), uint32(n)); // push tokens into the global `allTokens` collection (enumeration) allTokens.push32(uint32(_tokenId), uint32(n)); } /** * @dev Removes token from owner's local collection, * used internally to transfer or burn existing tokens * * @dev Unsafe: doesn't check for data structures consistency * (token existence, token ownership, etc.) * * @dev Must be kept private at all times. Inheriting smart contracts * may be interested in overriding this function. * * @param _tokenId token ID to remove */ function __removeLocal(uint256 _tokenId) internal virtual { // read token data, containing global and local indexes, owner address uint256 token = tokens[_tokenId]; // get a reference to the token's owner collection (local) uint32[] storage source = collections[address(uint160(token))]; // token index within the collection uint32 i = uint32(token >> 160); // get an ID of the last token in the collection uint32 sourceId = source[source.length - 1]; // if the token we're to remove from the collection is not the last one, // we need to move last token in the collection into index `i` if(i != source.length - 1) { // we put the last token in the collection to the position released // update last token local index to point to proper place in the collection // preserve global index and ownership info tokens[sourceId] = tokens[sourceId] // |unused |global | local | ownership information (address) | & 0x00000000FFFFFFFF00000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF | uint192(i) << 160; // put it into the position `i` within the collection source[i] = sourceId; } // trim the collection by removing last element source.pop(); // clear token approval (also emits an Approval event) __clearApproval(address(uint160(token)), _tokenId); } /** * @dev Removes token from both local and global collections (enumerations), * used internally to burn existing tokens * * @dev Unsafe: doesn't check for data structures consistency * (token existence, token ownership, etc.) * * @dev Must be kept private at all times. Inheriting smart contracts * may be interested in overriding this function. * * @param _tokenId token ID to remove */ function __removeToken(uint256 _tokenId) internal virtual { // remove token from owner's (local) collection first __removeLocal(_tokenId); // token index within the global collection uint32 i = uint32(tokens[_tokenId] >> 192); // delete the token delete tokens[_tokenId]; // get an ID of the last token in the collection uint32 lastId = allTokens[allTokens.length - 1]; // if the token we're to remove from the collection is not the last one, // we need to move last token in the collection into index `i` if(i != allTokens.length - 1) { // we put the last token in the collection to the position released // update last token global index to point to proper place in the collection // preserve local index and ownership info tokens[lastId] = tokens[lastId] // |unused |global | local | ownership information (address) | & 0x0000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF | uint224(i) << 192; // put it into the position `i` within the collection allTokens[i] = lastId; } // trim the collection by removing last element allTokens.pop(); } // ----- End: auxiliary internal/private functions ----- } // 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 Address Utils * * @dev Utility library of inline functions on addresses * * @dev Copy of the Zeppelin's library: * https://github.com/gnosis/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol */ library AddressUtils { /** * @notice Checks if the target address is a contract * * @dev It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * @dev 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 * * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { // a variable to load `extcodesize` to uint256 size = 0; // 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. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Array Utils * * @notice Solidity doesn't always work with arrays in an optimal way. * This library collects functions helping to optimize gas usage * when working with arrays in Solidity. * * @dev One of the most important use cases for arrays is "tight" arrays - * arrays which store values significantly less than 256-bits numbers */ library ArrayUtils { /** * @dev Pushes `n` 32-bits values sequentially into storage allocated array `data` * starting from the 32-bits value `v0` * * @dev Optimizations comparing to non-assembly implementation: * - reads+writes to array size slot only once (instead of `n` times) * - reads from the array data slots only once (instead of `7n/8` times) * - writes into array data slots `n/8` times (instead of `n` times) * * @dev Maximum gas saving estimate: ~3n sstore, or 15,000 * n * * @param data storage array pointer to an array of 32-bits elements * @param v0 first number to push into the array * @param n number of values to push, pushes [v0, ..., v0 + n - 1] */ function push32(uint32[] storage data, uint32 v0, uint32 n) internal { // we're going to write 32-bits values into 256-bits storage slots of the array // each 256-slot can store up to 8 32-bits sub-blocks, it can also be partially empty assembly { // for dynamic arrays their slot (array.slot) contains the array length // array data is stored separately in consequent storage slots starting // from the slot with the address keccak256(array.slot) // read the array length into `len` and increase it by `n` let len := sload(data.slot) sstore(data.slot, add(len, n)) // find where to write elements and store this location into `loc` // load array storage slot number into memory onto position 0, // calculate the keccak256 of the slot number (first 32 bytes at position 0) // - this will point to the beginning of the array, // so we add array length divided by 8 to point to the last array slot mstore(0, data.slot) let loc := add(keccak256(0, 32), div(len, 8)) // if we start writing data into already partially occupied slot (`len % 8 != 0`) // we need to modify the contents of that slot: read it and rewrite it let offset := mod(len, 8) if not(iszero(offset)) { // how many 32-bits sub-blocks left in the slot let left := sub(8, offset) // update the `left` value not to exceed `n` if gt(left, n) { left := n } // load the contents of the first slot (partially occupied) let v256 := sload(loc) // write the slot in 32-bits sub-blocks for { let j := 0 } lt(j, left) { j := add(j, 1) } { // write sub-block `j` at offset: `(j + offset) * 32` bits, length: 32-bits // v256 |= (v0 + j) << (j + offset) * 32 v256 := or(v256, shl(mul(add(j, offset), 32), add(v0, j))) } // write first slot back, it can be still partially occupied, it can also be full sstore(loc, v256) // update `loc`: move to the next slot loc := add(loc, 1) // update `v0`: increment by number of values pushed v0 := add(v0, left) // update `n`: decrement by number of values pushed n := sub(n, left) } // rest of the slots (if any) are empty and will be only written to // write the array in 256-bits (8x32) slots // `i` iterates [0, n) with the 256-bits step, which is 8 taken `n` is 32-bits long for { let i := 0 } lt(i, n) { i := add(i, 8) } { // how many 32-bits sub-blocks left in the slot let left := 8 // update the `left` value not to exceed `n` if gt(left, n) { left := n } // init the 256-bits slot value let v256 := 0 // write the slot in 32-bits sub-blocks for { let j := 0 } lt(j, left) { j := add(j, 1) } { // write sub-block `j` at offset: `j * 32` bits, length: 32-bits // v256 |= (v0 + i + j) << j * 32 v256 := or(v256, shl(mul(j, 32), add(v0, add(i, j)))) } // write slot `i / 8` sstore(add(loc, div(i, 8)), v256) } } } } // 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; /** * @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. * * @dev Copy of the Zeppelin's library: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e/contracts/utils/cryptography/ECDSA.sol */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * 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] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // 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))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("invalid signature length"); } return recover(hash, v, r, s); } /** * @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) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "invalid signature 's' value" ); require(v == 27 || v == 28, "invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "invalid signature"); return signer; } /** * @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.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; } }
@inheritdoc ERC721/ delegate call to overloaded `safeTransferFrom()`, set data to ""
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public override { safeTransferFrom(_from, _to, _tokenId, ""); }
6,018,494
// not deployed pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/math/SafeMath.sol'; import './SoccerCoin.sol'; contract UserCreation is SoccerCoin { using SafeMath for uint256; event NewUser(address user, uint id, string username); struct User { string name; uint reputation; uint articleCount; uint penaltyCount; uint readyTime; bool busyResearcher; uint researchedArticlesCount; } User[] public users; uint totalUserCount = 0; mapping (address => uint) public ownerUserCount; mapping (address => uint) public findUserId; mapping (address => bool) public isResearcher; function createUser(string _name) public { //check if owner already has an account require(ownerUserCount[msg.sender] == 0); //create new User uint id = users.push(User(_name, 0, 0, 0, uint32(now), false, 0)).sub(1); //add user to owner to user count mapping ownerUserCount[msg.sender] = ownerUserCount[msg.sender].add(1); //add user to is researcher mapping isResearcher[msg.sender] = false; // add user id to find user by address mapping findUserId[msg.sender] = id; totalUserCount = totalUserCount.add(1); //for event new user emit NewUser(msg.sender, id, _name); } // test function to create a researcher function createResearcher() public { isResearcher[msg.sender] = true; } // end test funtion function findUserInfo() public view returns(string, uint, uint, uint, uint, bool){ // So you can only request you own info require(ownerUserCount[msg.sender] == 1); //look up id uint id = findUserId[msg.sender]; //return requested info return (users[id].name, users[id].reputation, users[id].articleCount, users[id].penaltyCount, users[id].readyTime, users[id].busyResearcher); } function _etToatalUserCount() public view returns(uint) { return totalUserCount; } }
test function to create a researcher
function createResearcher() public { isResearcher[msg.sender] = true; }
12,716,384
./full_match/5/0xcAe9A86F6E3F4272B54195734966425559c9C318/sources/StakingContract.sol
Check if we know this user Return all the tokens in the stakedToken Array for this user that are not -1 Otherwise, return empty array
function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } }
1,917,319
/************************************************************************* * This contract has been merged with solidify * https://github.com/tiesnetwork/solidify *************************************************************************/ pragma solidity ^0.4.11; /************************************************************************* * import "./StandardToken.sol" : start *************************************************************************/ /************************************************************************* * import "./SafeMath.sol" : start *************************************************************************/ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /************************************************************************* * import "./SafeMath.sol" : end *************************************************************************/ /** * @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 { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); uint256 public totalSupply; address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event Pause(); event Unpause(); bool public paused = false; using SafeMath for uint256; mapping (address => mapping (address => uint256)) internal allowed; mapping(address => uint256) balances; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function StandardToken() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); 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]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); 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 - 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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @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(); } } /************************************************************************* * import "./StandardToken.sol" : end *************************************************************************/ contract CoinsOpenToken is StandardToken { // Token informations string public constant name = "COT"; string public constant symbol = "COT"; uint8 public constant decimals = 18; uint public totalSupply = 23000000000000000000000000; uint256 public presaleSupply = 2000000000000000000000000; uint256 public saleSupply = 13000000000000000000000000; uint256 public reserveSupply = 8000000000000000000000000; uint256 public saleStartTime = 1511136000; /* Monday, November 20, 2017 12:00:00 AM */ uint256 public saleEndTime = 1513728000; /* Wednesday, December 20, 2017 12:00:00 AM */ uint256 public preSaleStartTime = 1508457600; /* Friday, October 20, 2017 12:00:00 AM */ uint256 public developerLock = 1500508800; uint256 public totalWeiRaised = 0; uint256 public preSaleTokenPrice = 1400; uint256 public saleTokenPrice = 700; mapping (address => uint256) lastDividend; mapping (uint256 =>uint256) dividendList; uint256 currentDividend = 0; uint256 dividendAmount = 0; struct BuyOrder { uint256 wether; address receiver; address payer; bool presale; } /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, bool presale); /** * event for notifying of a Ether received to distribute as dividend * @param amount of dividend received */ event DividendAvailable(uint amount); /** * event triggered when sending dividend to owner * @param receiver who is receiving the payout * @param amountofether paid received */ event SendDividend(address indexed receiver, uint amountofether); function() payable { if (msg.sender == owner) { giveDividend(); } else { buyTokens(msg.sender); } } function endSale() whenNotPaused { require (!isInSale()); require (saleSupply != 0); reserveSupply = reserveSupply.add(saleSupply); } /** * Buy tokens during the sale/presale * @param _receiver who should receive the tokens */ function buyTokens(address _receiver) payable whenNotPaused { require (msg.value != 0); require (_receiver != 0x0); require (isInSale()); bool isPresale = isInPresale(); if (!isPresale) { checkPresale(); } uint256 tokenPrice = saleTokenPrice; if (isPresale) { tokenPrice = preSaleTokenPrice; } uint256 tokens = (msg.value).mul(tokenPrice); if (isPresale) { if (presaleSupply < tokens) { msg.sender.transfer(msg.value); return; } } else { if (saleSupply < tokens) { msg.sender.transfer(msg.value); return; } } checkDividend(_receiver); TokenPurchase(msg.sender, _receiver, msg.value, tokens, isPresale); totalWeiRaised = totalWeiRaised.add(msg.value); Transfer(0x0, _receiver, tokens); balances[_receiver] = balances[_receiver].add(tokens); if (isPresale) { presaleSupply = presaleSupply.sub(tokens); } else { saleSupply = saleSupply.sub(tokens); } } /** * @dev Pay this function to add the dividends */ function giveDividend() payable whenNotPaused { require (msg.value != 0); dividendAmount = dividendAmount.add(msg.value); dividendList[currentDividend] = (msg.value).mul(10000000000).div(totalSupply); currentDividend = currentDividend.add(1); DividendAvailable(msg.value); } /** * @dev Returns true if we are still in pre sale period * @param _account The address to check and send dividends */ function checkDividend(address _account) whenNotPaused { if (lastDividend[_account] != currentDividend) { if (balanceOf(_account) != 0) { uint256 toSend = 0; for (uint i = lastDividend[_account]; i < currentDividend; i++) { toSend += balanceOf(_account).mul(dividendList[i]).div(10000000000); } if (toSend > 0 && toSend <= dividendAmount) { _account.transfer(toSend); dividendAmount = dividendAmount.sub(toSend); SendDividend(_account, toSend); } } lastDividend[_account] = currentDividend; } } /** * @dev transfer token for a specified address checking if they are dividends to pay * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { checkDividend(msg.sender); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another checking if they are dividends to pay * @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) { checkDividend(_from); return super.transferFrom(_from, _to, _value); } /** * @dev Returns true if we are still in pre sale period */ function isInPresale() constant returns (bool) { return saleStartTime > now; } /** * @dev Returns true if we are still in sale period */ function isInSale() constant returns (bool) { return saleEndTime >= now && preSaleStartTime <= now; } // @return true if the transaction can buy tokens function checkPresale() internal { if (!isInPresale() && presaleSupply > 0) { saleSupply = saleSupply.add(presaleSupply); presaleSupply = 0; } } /** * Distribute tokens from the reserve * @param _amount Amount to transfer * @param _receiver Address of the receiver */ function distributeReserveSupply(uint256 _amount, address _receiver) onlyOwner whenNotPaused { require (_amount <= reserveSupply); require (now >= developerLock); checkDividend(_receiver); balances[_receiver] = balances[_receiver].add(_amount); reserveSupply.sub(_amount); Transfer(0x0, _receiver, _amount); } /** * Withdraw some Ether from contract */ function withdraw(uint _amount) onlyOwner { require (_amount != 0); require (_amount < this.balance); (msg.sender).transfer(_amount); } /** * Withdraw Ether from contract */ function withdrawEverything() onlyOwner { (msg.sender).transfer(this.balance); } }
Withdraw some Ether from contract/
function withdraw(uint _amount) onlyOwner { require (_amount != 0); require (_amount < this.balance); (msg.sender).transfer(_amount); }
7,247,473
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IKeeperSubsidyPool.sol"; import "./interfaces/IUniswapRouterV2.sol"; import "./interfaces/IUniswapFactory.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./interfaces/IEToken.sol"; import "./interfaces/IEPoolPeriphery.sol"; import "./interfaces/IEPool.sol"; import "./utils/ControllerMixin.sol"; import "./utils/TokenUtils.sol"; import "./EPoolLibrary.sol"; import "hardhat/console.sol"; contract EPoolPeriphery is ControllerMixin, IEPoolPeriphery { using SafeERC20 for IERC20; using TokenUtils for IERC20; using TokenUtils for IEToken; IUniswapV2Factory public immutable override factory; IUniswapV2Router01 public immutable override router; // Keeper subsidy pool for making rebalancing via flash swaps capital neutral for msg.sender IKeeperSubsidyPool public immutable override keeperSubsidyPool; // supported EPools by the periphery mapping(address => bool) public override ePools; // max. allowed slippage between EPool oracle and uniswap when executing a flash swap uint256 public override maxFlashSwapSlippage; event IssuedEToken( address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user ); event RedeemedEToken( address indexed ePool, address indexed eToken, uint256 amount, uint256 amountA, uint256 amountB, address user ); event SetEPoolApproval(address indexed ePool, bool approval); event SetMaxFlashSwapSlippage(uint256 maxFlashSwapSlippage); event RecoveredToken(address token, uint256 amount); /** * @param _controller Address of the controller * @param _factory Address of the Uniswap V2 factory * @param _router Address of the Uniswap V2 router * @param _keeperSubsidyPool Address of keeper subsidiy pool * @param _maxFlashSwapSlippage Max. allowed slippage between EPool oracle and uniswap */ constructor( IController _controller, IUniswapV2Factory _factory, IUniswapV2Router01 _router, IKeeperSubsidyPool _keeperSubsidyPool, uint256 _maxFlashSwapSlippage ) ControllerMixin(_controller) { factory = _factory; router = _router; keeperSubsidyPool = _keeperSubsidyPool; maxFlashSwapSlippage = _maxFlashSwapSlippage; // e.g. 1.05e18 -> 5% slippage } /** * @notice Returns the address of the current Aggregator which provides the exchange rate between TokenA and TokenB * @return Address of aggregator */ function getController() external view override returns (address) { return address(controller); } /** * @notice Updates the Controller * @dev Can only called by an authorized sender * @param _controller Address of the new Controller * @return True on success */ function setController(address _controller) external override onlyDao("EPoolPeriphery: not dao") returns (bool) { _setController(_controller); return true; } /** * @notice Give or revoke approval a EPool for the EPoolPeriphery * @dev Can only called by the DAO or the guardian * @param ePool Address of the EPool * @param approval Boolean on whether approval for EPool should be given or revoked * @return True on success */ function setEPoolApproval( IEPool ePool, bool approval ) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) { if (approval) { // assuming EPoolPeriphery only holds funds within calls ePool.tokenA().approve(address(ePool), type(uint256).max); ePool.tokenB().approve(address(ePool), type(uint256).max); ePools[address(ePool)] = true; } else { ePool.tokenA().approve(address(ePool), 0); ePool.tokenB().approve(address(ePool), 0); ePools[address(ePool)] = false; } emit SetEPoolApproval(address(ePool), approval); return true; } /** * @notice Set max. slippage between EPool oracle and uniswap when performing flash swap * @dev Can only be callede by the DAO or the guardian * @param _maxFlashSwapSlippage Max. flash swap slippage * @return True on success */ function setMaxFlashSwapSlippage( uint256 _maxFlashSwapSlippage ) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) { maxFlashSwapSlippage = _maxFlashSwapSlippage; emit SetMaxFlashSwapSlippage(maxFlashSwapSlippage); return true; } /** * @notice Issues an amount of EToken for maximum amount of TokenA * @dev Reverts if maxInputAmountA is exceeded. Unused amount of TokenA is refunded to msg.sender. * Requires setting allowance for TokenA. * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to issue * @param maxInputAmountA Max. amount of TokenA to deposit * @param deadline Timestamp at which tx expires * @return True on success */ function issueForMaxTokenA( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountA, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); tokenA.safeTransferFrom(msg.sender, address(this), maxInputAmountA); IEPool.Tranche memory t = ePool.getTranche(eToken); (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); // swap part of input amount for amountB require(maxInputAmountA >= amountA, "EPoolPeriphery: insufficient max. input"); uint256 amountAToSwap = maxInputAmountA - amountA; address[] memory path = new address[](2); path[0] = address(tokenA); path[1] = address(tokenB); tokenA.approve(address(router), amountAToSwap); uint256[] memory amountsOut = router.swapTokensForExactTokens( amountB, amountAToSwap, path, address(this), deadline ); // do the deposit (TokenA is already approved) ePool.issueExact(eToken, amount); // transfer EToken to msg.sender IERC20(eToken).safeTransfer(msg.sender, amount); // refund unused maxInputAmountA -= amountA + amountASwappedForAmountB tokenA.safeTransfer(msg.sender, maxInputAmountA - amountA - amountsOut[0]); emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Issues an amount of EToken for maximum amount of TokenB * @dev Reverts if maxInputAmountB is exceeded. Unused amount of TokenB is refunded to msg.sender. * Requires setting allowance for TokenB. * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to issue * @param maxInputAmountB Max. amount of TokenB to deposit * @param deadline Timestamp at which tx expires * @return True on success */ function issueForMaxTokenB( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountB, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); tokenB.safeTransferFrom(msg.sender, address(this), maxInputAmountB); IEPool.Tranche memory t = ePool.getTranche(eToken); (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( t, amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); // swap part of input amount for amountB require(maxInputAmountB >= amountB, "EPoolPeriphery: insufficient max. input"); uint256 amountBToSwap = maxInputAmountB - amountB; address[] memory path = new address[](2); path[0] = address(tokenB); path[1] = address(tokenA); tokenB.approve(address(router), amountBToSwap); uint256[] memory amountsOut = router.swapTokensForExactTokens( amountA, amountBToSwap, path, address(this), deadline ); // do the deposit (TokenB is already approved) ePool.issueExact(eToken, amount); // transfer EToken to msg.sender IERC20(eToken).safeTransfer(msg.sender, amount); // refund unused maxInputAmountB -= amountB + amountBSwappedForAmountA tokenB.safeTransfer(msg.sender, maxInputAmountB - amountB - amountsOut[0]); emit IssuedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Redeems an amount of EToken for a min. amount of TokenA * @dev Reverts if minOutputA is not met. Requires setting allowance for EToken * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to redeem * @param minOutputA Min. amount of TokenA to withdraw * @param deadline Timestamp at which tx expires * @return True on success */ function redeemForMinTokenA( IEPool ePool, address eToken, uint256 amount, uint256 minOutputA, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount); // do the withdraw IERC20(eToken).approve(address(ePool), amount); (uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount); // convert amountB withdrawn from EPool into TokenA address[] memory path = new address[](2); path[0] = address(tokenB); path[1] = address(tokenA); tokenB.approve(address(router), amountB); uint256[] memory amountsOut = router.swapExactTokensForTokens( amountB, 0, path, address(this), deadline ); uint256 outputA = amountA + amountsOut[1]; require(outputA >= minOutputA, "EPoolPeriphery: insufficient output amount"); IERC20(tokenA).safeTransfer(msg.sender, outputA); emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Redeems an amount of EToken for a min. amount of TokenB * @dev Reverts if minOutputB is not met. Requires setting allowance for EToken * @param ePool Address of the EPool * @param eToken Address of the EToken of the tranche * @param amount Amount of EToken to redeem * @param minOutputB Min. amount of TokenB to withdraw * @param deadline Timestamp at which tx expires * @return True on success */ function redeemForMinTokenB( IEPool ePool, address eToken, uint256 amount, uint256 minOutputB, uint256 deadline ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (IERC20 tokenA, IERC20 tokenB) = (ePool.tokenA(), ePool.tokenB()); IERC20(eToken).safeTransferFrom(msg.sender, address(this), amount); // do the withdraw IERC20(eToken).approve(address(ePool), amount); (uint256 amountA, uint256 amountB) = ePool.redeemExact(eToken, amount); // convert amountB withdrawn from EPool into TokenA address[] memory path = new address[](2); path[0] = address(tokenA); path[1] = address(tokenB); tokenA.approve(address(router), amountA); uint256[] memory amountsOut = router.swapExactTokensForTokens( amountA, 0, path, address(this), deadline ); uint256 outputB = amountB + amountsOut[1]; require(outputB >= minOutputB, "EPoolPeriphery: insufficient output amount"); IERC20(tokenB).safeTransfer(msg.sender, outputB); emit RedeemedEToken(address(ePool), eToken, amount, amountA, amountB, msg.sender); return true; } /** * @notice Rebalances a EPool. Capital required for rebalancing is obtained via a flash swap. * The potential slippage between the EPool oracle and uniswap is covered by the KeeperSubsidyPool. * @dev Fails if maxFlashSwapSlippage is exceeded in uniswapV2Call * @param ePool Address of the EPool to rebalance * @param fracDelta Fraction of the delta to rebalance (1e18 for rebalancing the entire delta) * @return True on success */ function rebalanceWithFlashSwap( IEPool ePool, uint256 fracDelta ) external override returns (bool) { require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); (address tokenA, address tokenB) = (address(ePool.tokenA()), address(ePool.tokenB())); (uint256 deltaA, uint256 deltaB, uint256 rChange, ) = EPoolLibrary.delta( ePool.getTranches(), ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(address(tokenA), address(tokenB))); // map deltaA, deltaB to amountOut0, amountOut1 uint256 amountOut0; uint256 amountOut1; if (rChange == 0) { (amountOut0, amountOut1) = (address(tokenA) == pair.token0()) ? (uint256(0), deltaB) : (deltaB, uint256(0)); } else { (amountOut0, amountOut1) = (address(tokenA) == pair.token0()) ? (deltaA, uint256(0)) : (uint256(0), deltaA); } bytes memory data = abi.encode(ePool, fracDelta); pair.swap(amountOut0, amountOut1, address(this), data); return true; } /** * @notice rebalanceAllWithFlashSwap callback called by the uniswap pair * @dev Trusts that deltas are actually forwarded by the EPool. * Verifies that funds are forwarded from flash swap of the uniswap pair. * param sender Address of the flash swap initiator * param amount0 * param amount1 * @param data Data forwarded in the flash swap */ function uniswapV2Call( address /* sender */, // skip sender check, check for forwarded funds by flash swap is sufficient uint256 /* amount0 */, uint256 /* amount1 */, bytes calldata data ) external { (IEPool ePool, uint256 fracDelta) = abi.decode(data, (IEPool, uint256)); require(ePools[address(ePool)], "EPoolPeriphery: unapproved EPool"); // fails if no funds are forwarded in the flash swap callback from the uniswap pair // TokenA, TokenB are already approved (uint256 deltaA, uint256 deltaB, uint256 rChange, ) = ePool.rebalance(fracDelta); address[] memory path = new address[](2); // [0] flash swap repay token, [1] flash lent token uint256 amountsIn; // flash swap repay amount uint256 deltaOut; if (rChange == 0) { // release TokenA, add TokenB to EPool -> flash swap TokenB, repay with TokenA path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); (amountsIn, deltaOut) = (router.getAmountsIn(deltaB, path)[0], deltaA); } else { // add TokenA, release TokenB to EPool -> flash swap TokenA, repay with TokenB path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); (amountsIn, deltaOut) = (router.getAmountsIn(deltaA, path)[0], deltaB); } // if slippage is negative request subsidy, if positive top of KeeperSubsidyPool if (amountsIn > deltaOut) { require( amountsIn * EPoolLibrary.sFactorI / deltaOut <= maxFlashSwapSlippage, "EPoolPeriphery: excessive slippage" ); keeperSubsidyPool.requestSubsidy(path[0], amountsIn - deltaOut); } else if (amountsIn < deltaOut) { IERC20(path[0]).safeTransfer(address(keeperSubsidyPool), deltaOut - amountsIn); } // repay flash swap by sending amountIn to pair IERC20(path[0]).safeTransfer(msg.sender, amountsIn); } /** * @notice Recovers untracked amounts * @dev Can only called by an authorized sender * @param token Address of the token * @param amount Amount to recover * @return True on success */ function recover(IERC20 token, uint256 amount) external override onlyDao("EPool: not dao") returns (bool) { token.safeTransfer(msg.sender, amount); emit RecoveredToken(address(token), amount); return true; } /* ------------------------------------------------------------------------------------------------------- */ /* view and pure methods */ /* ------------------------------------------------------------------------------------------------------- */ function minInputAmountAForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 minTokenA) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); address[] memory path = new address[](2); path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); minTokenA = amountA + router.getAmountsIn(amountB, path)[0]; } // does not include price impact, which would result in a smaller EToken amount function eTokenForMinInputAmountA_Unsafe( IEPool ePool, address eToken, uint256 minInputAmountA ) external view returns (uint256 amount) { IEPool.Tranche memory t = ePool.getTranche(eToken); uint256 rate = ePool.getRate(); uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB); (uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenA( minInputAmountA, ratio, rate, sFactorA, sFactorB ); return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB); } function minInputAmountBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 minTokenB) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); address[] memory path = new address[](2); path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); minTokenB = amountB + router.getAmountsIn(amountA, path)[0]; } // does not include price impact, which would result in a smaller EToken amount function eTokenForMinInputAmountB_Unsafe( IEPool ePool, address eToken, uint256 minInputAmountB ) external view returns (uint256 amount) { IEPool.Tranche memory t = ePool.getTranche(eToken); uint256 rate = ePool.getRate(); uint256 sFactorA = ePool.sFactorA(); uint256 sFactorB = ePool.sFactorB(); uint256 ratio = EPoolLibrary.currentRatio(t, rate, sFactorA, sFactorB); (uint256 amountAIdeal, uint256 amountBIdeal) = EPoolLibrary.tokenATokenBForTokenB( minInputAmountB, ratio, rate, sFactorA, sFactorB ); return EPoolLibrary.eTokenForTokenATokenB(t, amountAIdeal, amountBIdeal, rate, sFactorA, sFactorB); } function maxOutputAmountAForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 maxTokenA) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); uint256 feeRate = ePool.feeRate(); amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI; amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI; address[] memory path = new address[](2); path[0] = address(ePool.tokenB()); path[1] = address(ePool.tokenA()); maxTokenA = amountA + router.getAmountsOut(amountB, path)[1]; } function maxOutputAmountBForEToken( IEPool ePool, address eToken, uint256 amount ) external view returns (uint256 maxTokenB) { (uint256 amountA, uint256 amountB) = EPoolLibrary.tokenATokenBForEToken( ePool.getTranche(eToken), amount, ePool.getRate(), ePool.sFactorA(), ePool.sFactorB() ); uint256 feeRate = ePool.feeRate(); amountA = amountA - amountA * feeRate / EPoolLibrary.sFactorI; amountB = amountB - amountB * feeRate / EPoolLibrary.sFactorI; address[] memory path = new address[](2); path[0] = address(ePool.tokenA()); path[1] = address(ePool.tokenB()); maxTokenB = amountB + router.getAmountsOut(amountA, path)[1]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; interface IKeeperSubsidyPool { function getController() external view returns (address); function setController(address _controller) external returns (bool); function setBeneficiary(address beneficiary, bool canRequest) external returns (bool); function isBeneficiary(address beneficiary) external view returns (bool); function requestSubsidy(address token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: GNU pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: GNU pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed tokenA, address pair, uint); 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 feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } // SPDX-License-Identifier: GNU pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amountA); event Burn(address indexed sender, uint amount0, uint amountA, address indexed to); event Swap( address indexed sender, uint amount0In, uint amountAIn, uint amount0Out, uint amountAOut, address indexed to ); event Sync(uint112 reserve0, uint112 reserveA); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function tokenA() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserveA, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amountA); function swap(uint amount0Out, uint amountAOut, address to, bytes calldata data) external; function skim(address to) external; function sync() external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEToken is IERC20 { function getController() external view returns (address); function setController(address _controller) external returns (bool); function mint(address account, uint256 amount) external returns (bool); function burn(address account, uint256 amount) external returns (bool); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "./IKeeperSubsidyPool.sol"; import "./IUniswapRouterV2.sol"; import "./IUniswapFactory.sol"; import "./IEPool.sol"; interface IEPoolPeriphery { function getController() external view returns (address); function setController(address _controller) external returns (bool); function factory() external view returns (IUniswapV2Factory); function router() external view returns (IUniswapV2Router01); function ePools(address) external view returns (bool); function keeperSubsidyPool() external view returns (IKeeperSubsidyPool); function maxFlashSwapSlippage() external view returns (uint256); function setEPoolApproval(IEPool ePool, bool approval) external returns (bool); function setMaxFlashSwapSlippage(uint256 _maxFlashSwapSlippage) external returns (bool); function issueForMaxTokenA( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountA, uint256 deadline ) external returns (bool); function issueForMaxTokenB( IEPool ePool, address eToken, uint256 amount, uint256 maxInputAmountB, uint256 deadline ) external returns (bool); function redeemForMinTokenA( IEPool ePool, address eToken, uint256 amount, uint256 minOutputA, uint256 deadline ) external returns (bool); function redeemForMinTokenB( IEPool ePool, address eToken, uint256 amount, uint256 minOutputB, uint256 deadline ) external returns (bool); function rebalanceWithFlashSwap(IEPool ePool, uint256 fracDelta) external returns (bool); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IEToken.sol"; interface IEPool { struct Tranche { IEToken eToken; uint256 sFactorE; uint256 reserveA; uint256 reserveB; uint256 targetRatio; } function getController() external view returns (address); function setController(address _controller) external returns (bool); function tokenA() external view returns (IERC20); function tokenB() external view returns (IERC20); function sFactorA() external view returns (uint256); function sFactorB() external view returns (uint256); function getTranche(address eToken) external view returns (Tranche memory); function getTranches() external view returns(Tranche[] memory _tranches); function addTranche(uint256 targetRatio, string memory eTokenName, string memory eTokenSymbol) external returns (bool); function getAggregator() external view returns (address); function setAggregator(address oracle, bool inverseRate) external returns (bool); function rebalanceMinRDiv() external view returns (uint256); function rebalanceInterval() external view returns (uint256); function lastRebalance() external view returns (uint256); function feeRate() external view returns (uint256); function cumulativeFeeA() external view returns (uint256); function cumulativeFeeB() external view returns (uint256); function setFeeRate(uint256 _feeRate) external returns (bool); function transferFees() external returns (bool); function getRate() external view returns (uint256); function rebalance(uint256 fracDelta) external returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv); function issueExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function redeemExact(address eToken, uint256 amount) external returns (uint256 amountA, uint256 amountB); function recover(IERC20 token, uint256 amount) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "../interfaces/IController.sol"; contract ControllerMixin { event SetController(address controller); IController internal controller; constructor(IController _controller) { controller = _controller; } modifier onlyDao(string memory revertMsg) { require(msg.sender == controller.dao(), revertMsg); _; } modifier onlyDaoOrGuardian(string memory revertMsg) { require(controller.isDaoOrGuardian(msg.sender), revertMsg); _; } modifier issuanceNotPaused(string memory revertMsg) { require(controller.pausedIssuance() == false, revertMsg); _; } function _setController(address _controller) internal { controller = IController(_controller); emit SetController(_controller); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IERC20Optional.sol"; library TokenUtils { function decimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSignature("decimals()")); require(success, "TokenUtils: no decimals"); uint8 _decimals = abi.decode(data, (uint8)); return _decimals; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IETokenFactory.sol"; import "./interfaces/IEToken.sol"; import "./interfaces/IEPool.sol"; import "./utils/TokenUtils.sol"; import "./utils/Math.sol"; library EPoolLibrary { using TokenUtils for IERC20; uint256 internal constant sFactorI = 1e18; // internal scaling factor (18 decimals) /** * @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit) * currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals */ function currentRatio( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { if (t.reserveA == 0 || t.reserveB == 0) { if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio; if (t.reserveA == 0) return 0; if (t.reserveB == 0) return type(uint256).max; } return ((t.reserveA * rate / sFactorA) * sFactorI) / (t.reserveB * sFactorI / sFactorB); } /** * @notice Returns the deviation of reserveA and reserveB from target ratio * currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity * currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity * deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.targetRatio) * deltaB := deltaA * rate */ function trancheDelta( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) { rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0; deltaA = ( Math.abs(t.reserveA, tokenAForTokenB(t.reserveB, t.targetRatio, rate, sFactorA, sFactorB)) * sFactorA ) / (sFactorA + (t.targetRatio * sFactorA / sFactorI)); // (convert to TokenB precision first to avoid altering deltaA) deltaB = ((deltaA * sFactorB / sFactorA) * rate) / sFactorI; } /** * @notice Returns the sum of the tranches reserve deltas */ function delta( IEPool.Tranche[] memory ts, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { uint256 totalReserveA; int256 totalDeltaA; int256 totalDeltaB; for (uint256 i = 0; i < ts.length; i++) { totalReserveA += ts[i].reserveA; (uint256 _deltaA, uint256 _deltaB, uint256 _rChange) = trancheDelta( ts[i], rate, sFactorA, sFactorB ); (totalDeltaA, totalDeltaB) = (_rChange == 0) ? (totalDeltaA - int256(_deltaA), totalDeltaB + int256(_deltaB)) : (totalDeltaA + int256(_deltaA), totalDeltaB - int256(_deltaB)); } if (totalDeltaA > 0) { (deltaA, deltaB, rChange) = (uint256(totalDeltaA), uint256(-totalDeltaB), 1); } else { (deltaA, deltaB, rChange) = (uint256(-totalDeltaA), uint256(totalDeltaB), 0); } rDiv = (totalReserveA == 0) ? 0 : deltaA * EPoolLibrary.sFactorI / totalReserveA; } /** * @notice how much EToken can be issued, redeemed for amountA and amountB * initial issuance / last redemption: sqrt(amountA * amountB) * subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply */ function eTokenForTokenATokenB( IEPool.Tranche memory t, uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256) { uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB); if (t.reserveA + t.reserveB == 0) { return (Math.sqrt((amountsA * t.sFactorE / sFactorA) * t.sFactorE)); } uint256 reservesA = totalA(t.reserveA, t.reserveB, rate, sFactorA, sFactorB); uint256 share = ((amountsA * t.sFactorE / sFactorA) * t.sFactorE) / (reservesA * t.sFactorE / sFactorA); return share * t.eToken.totalSupply() / t.sFactorE; } /** * @notice Given an amount of EToken, how much TokenA and TokenB have to be deposited, withdrawn for it * initial issuance / last redemption: sqrt(amountA * amountB) -> such that the inverse := EToken amount ** 2 * subsequent issuances / non nullifying redemptions: claim on EToken supply * reserveA/B */ function tokenATokenBForEToken( IEPool.Tranche memory t, uint256 amount, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256 amountA, uint256 amountB) { if (t.reserveA + t.reserveB == 0) { uint256 amountsA = amount * sFactorA / t.sFactorE; (amountA, amountB) = tokenATokenBForTokenA( amountsA * amountsA / sFactorA , t.targetRatio, rate, sFactorA, sFactorB ); } else { uint256 eTokenTotalSupply = t.eToken.totalSupply(); if (eTokenTotalSupply == 0) return(0, 0); uint256 share = amount * t.sFactorE / eTokenTotalSupply; amountA = share * t.reserveA / t.sFactorE; amountB = share * t.reserveB / t.sFactorE; } } /** * @notice Given amountB, which amountA is required such that amountB / amountA is equal to the ratio * amountA := amountBInTokenA * ratio */ function tokenAForTokenB( uint256 amountB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountB * sFactorI / sFactorB) * ratio) / rate) * sFactorA / sFactorI; } /** * @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio * amountB := amountAInTokenB / ratio */ function tokenBForTokenA( uint256 amountA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenA, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := total - (total / (1 + ratio)) == (total * ratio) / (1 + ratio) * amountB := (total / (1 + ratio)) * rate */ function tokenATokenBForTokenA( uint256 _totalA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = _totalA - (_totalA * sFactorI / (sFactorI + ratio)); amountB = (((_totalA * sFactorI / sFactorA) * rate) / (sFactorI + ratio)) * sFactorB / sFactorI; } /** * @notice Given an amount of TokenB, how can it be split up proportionally into amountA and amountB * according to the ratio * amountA := (total * ratio) / (rate * (1 + ratio)) * amountB := total / (1 + ratio) */ function tokenATokenBForTokenB( uint256 _totalB, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 amountA, uint256 amountB) { amountA = ((((_totalB * sFactorI / sFactorB) * ratio) / (sFactorI + ratio)) * sFactorA) / rate; amountB = (_totalB * sFactorI) / (sFactorI + ratio); } /** * @notice Return the total value of amountA and amountB denominated in TokenA * totalA := amountA + (amountB / rate) */ function totalA( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalA) { return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI; } /** * @notice Return the total value of amountA and amountB denominated in TokenB * totalB := amountB + (amountA * rate) */ function totalB( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalB) { return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI; } /** * @notice Return the withdrawal fee for a given amount of TokenA and TokenB * feeA := amountA * feeRate * feeB := amountB * feeRate */ function feeAFeeBForTokenATokenB( uint256 amountA, uint256 amountB, uint256 feeRate ) internal pure returns (uint256 feeA, uint256 feeB) { feeA = amountA * feeRate / EPoolLibrary.sFactorI; feeB = amountB * feeRate / EPoolLibrary.sFactorI; } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // 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: Apache-2.0 pragma solidity ^0.8.1; pragma experimental ABIEncoderV2; interface IController { function dao() external view returns (address); function guardian() external view returns (address); function isDaoOrGuardian(address sender) external view returns (bool); function setDao(address _dao) external returns (bool); function setGuardian(address _guardian) external returns (bool); function feesOwner() external view returns (address); function pausedIssuance() external view returns (bool); function setFeesOwner(address _feesOwner) external returns (bool); function setPausedIssuance(bool _pausedIssuance) external returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; /** * @dev Interface of the the optional methods of the ERC20 standard as defined in the EIP. */ interface IERC20Optional { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.1; import "./IEToken.sol"; interface IETokenFactory { function getController() external view returns (address); function setController(address _controller) external returns (bool); function createEToken(string memory name, string memory symbol) external returns (IEToken); } // SPDX-License-Identifier: GNU pragma solidity ^0.8.1; library Math { function abs(uint256 a, uint256 b) internal pure returns (uint256) { return (a > b) ? a - b : b - a; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } }
Set max. slippage between EPool oracle and uniswap when performing flash swap Can only be callede by the DAO or the guardian _maxFlashSwapSlippage Max. flash swap slippage return True on success/
function setMaxFlashSwapSlippage( uint256 _maxFlashSwapSlippage ) external override onlyDaoOrGuardian("EPoolPeriphery: not dao or guardian") returns (bool) { maxFlashSwapSlippage = _maxFlashSwapSlippage; emit SetMaxFlashSwapSlippage(maxFlashSwapSlippage); return true; }
1,224,780
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@chainlink/contracts/src/v0.8/interfaces/KeeperCompatibleInterface.sol"; interface INFTMinter { function getNFTAttributes(uint256 NFTID) external returns(uint256 agility, uint256 strength, uint256 charm, uint256 sneak, uint256 health); function changeNFTAttributes(uint256 NFTID, uint256 health, uint256 agility, uint256 strength, uint256 sneak, uint256 charm) external returns (bool); } contract BreakInGame is VRFConsumerBase, Ownable, KeeperCompatibleInterface{ bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; address kovanKeeperRegistryAddress = 0x4Cb093f226983713164A62138C3F718A5b595F73; modifier onlyKeeper() { require(msg.sender == kovanKeeperRegistryAddress); _; } uint256 hospitalBill = 1000*10**18; uint256 public lastCheckIn = block.timestamp; uint256 public checkInTimeInterval = 864000; //default to six months address public nextOwner; INFTMinter IBreakInNFTMinter = INFTMinter(0xCAE12a0021d4d87590931bFb0606Dc103876cB0E); IERC721 breakInNFT = IERC721(0xCAE12a0021d4d87590931bFb0606Dc103876cB0E); //address of breakInNFTs IERC20 deSocialNetToken = IERC20(0xAe0f650F39B943F738a790519C3556bf6f8C92F1); //adress of desocialNet token /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9 * LINK token address: 0xa36085F69e2889c224210F603D836748e7dC0088 * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4 */ constructor() VRFConsumerBase( 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9, // VRF Coordinator 0xa36085F69e2889c224210F603D836748e7dC0088 // LINK Token ) { keyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4; fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network) } struct scenarios{ string name; uint256 riskBaseDifficulty; uint256 payoutAmountBase; } struct NFTCharacter { uint256 born; uint256 health; uint256 agility; uint256 strength; uint256 sneak; uint256 charm; uint256 characterID; } struct depostedCharacter { uint256 NFTID; bool isDeposited; bool arrested; uint256 freetoPlayAgain; bool playingPVP; uint256 canStopPlayingPVP; uint256 lootingTimeout; uint256 health; uint256 agility; uint256 strength; uint256 sneak; uint256 charm; } struct gamePlay { address player; uint256 scenario; uint256 breakInStyle; uint256 difficultyLevel; uint256 health; uint256 agility; uint256 strength; uint256 sneak; uint256 charm; } struct jailBreak { address player; uint256 breakInStyle; uint256 health; uint256 agility; uint256 strength; uint256 sneak; uint256 charm; address targetPlayer; // who you want to break out } struct PvP { address player; uint256 breakInStyle; uint256 difficultyLevel; uint256 health; uint256 agility; uint256 strength; uint256 sneak; uint256 charm; address targetPlayer; // who you want to steal from uint256 targetPlayerHealth; uint256 targetPlayerAgility; uint256 targetPlayerStrength; uint256 targetPlayerSneak; uint256 targetPlayerCharm; } struct gameModes { uint256 gameMode; // 0 if robbing, 1 if jailBreak, 2 if PvP } event gameCode(bytes32 requestID, address player, uint256 code); uint256 differentGameScenarios; mapping(uint256 => scenarios) public gameScenarios; // current gameScenarios for robbing mapping(bytes32 => PvP) currentPVPGamePlays; // for if you are trying to steal from a player mapping(bytes32 => gamePlay) currentGamePlays; // this is for a standard robbing gameplay mapping(bytes32 => gameModes) currentGameMode; // this allows for a quick compare statement to determine which game to play to safe gas mapping(bytes32 => jailBreak) currentJailBreaks; // this is for players trying to break out a buddy mapping(address => depostedCharacter) public NFTCharacterDepositLedger; // Players deposit their NFT into this contract to Play mapping(address => uint256) public jewelDepositLedger; // Players must deposit their loot to play PvP function changeHospitalBill(uint256 newHospitalBill) public onlyOwner { hospitalBill = newHospitalBill; lastCheckIn = block.timestamp; } function addScenario(string memory name, uint16 riskBaseDifficulty, uint256 payoutAmountBase) public onlyOwner{ uint256 gameScenarioID = differentGameScenarios; gameScenarios[gameScenarioID].name = name; gameScenarios[gameScenarioID].riskBaseDifficulty = riskBaseDifficulty; gameScenarios[gameScenarioID].payoutAmountBase = payoutAmountBase; differentGameScenarios += 1; } function modifyScenario(uint256 scenarioNumber, string memory name, uint16 riskBaseDifficulty, uint16 payoutAmountBase) public onlyOwner{ gameScenarios[scenarioNumber].riskBaseDifficulty = riskBaseDifficulty; // scenarios can be removed by effectily raising the riskbase difficult level so high no one would bother playing it and making payoutAmountBase 0 gameScenarios[scenarioNumber].payoutAmountBase = payoutAmountBase; gameScenarios[scenarioNumber].name = name; } function depositNFT(uint256 NFTID) public { // users Must Deposit a character to play require(NFTCharacterDepositLedger[msg.sender].isDeposited != true,"Character Already Deposited"); breakInNFT.transferFrom(msg.sender, address(this),NFTID); NFTCharacterDepositLedger[msg.sender].NFTID = NFTID; NFTCharacterDepositLedger[msg.sender].isDeposited = true; // (NFTCharacterDepositLedger[msg.sender].agility,NFTCharacterDepositLedger[msg.sender].strength,NFTCharacterDepositLedger[msg.sender].charm,NFTCharacterDepositLedger[msg.sender].sneak,NFTCharacterDepositLedger[msg.sender].health)= IBreakInNFTMinter.getNFTAttributes(NFTCharacterDepositLedger[msg.sender].NFTID); } function withdrawNFT() public { require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"No Character Deposited"); require(NFTCharacterDepositLedger[msg.sender].arrested == false,"Character in Prison"); IBreakInNFTMinter.changeNFTAttributes(NFTCharacterDepositLedger[msg.sender].NFTID, // modify attributes of player if experience was gained or health lost NFTCharacterDepositLedger[msg.sender].health, NFTCharacterDepositLedger[msg.sender].agility, NFTCharacterDepositLedger[msg.sender].strength, NFTCharacterDepositLedger[msg.sender].sneak, NFTCharacterDepositLedger[msg.sender].charm); breakInNFT.transferFrom(address(this), msg.sender,NFTCharacterDepositLedger[msg.sender].NFTID); NFTCharacterDepositLedger[msg.sender].isDeposited = false; } function depositJewels(uint256 amountToDeposit) public { require(NFTCharacterDepositLedger[msg.sender].arrested == false,"Character in Prison"); deSocialNetToken.transferFrom(msg.sender, address(this),amountToDeposit); jewelDepositLedger[msg.sender] += amountToDeposit; } function withdrawJewels(uint256 amountToWithdraw) public { require(jewelDepositLedger[msg.sender] >= amountToWithdraw, "Trying to withdraw too much money" ); deSocialNetToken.transfer(msg.sender,amountToWithdraw); jewelDepositLedger[msg.sender] -= amountToWithdraw; } function startPlayPVP() public { require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"Character Not deposited"); NFTCharacterDepositLedger[msg.sender].playingPVP = true; NFTCharacterDepositLedger[msg.sender].canStopPlayingPVP = block.timestamp + 604800; // players must play a minimum 7 days to prevent players entering and exiting quickly; } function stopPlayPVP() public { require(block.timestamp >= NFTCharacterDepositLedger[msg.sender].canStopPlayingPVP,"You must wait 7 days since you started playing"); NFTCharacterDepositLedger[msg.sender].playingPVP = false; } function hospitalVisit() public { require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"Character Not Deposited"); require(NFTCharacterDepositLedger[msg.sender].health < 100); require(jewelDepositLedger[msg.sender] >= (hospitalBill)); jewelDepositLedger[msg.sender] -= hospitalBill; NFTCharacterDepositLedger[msg.sender].health = 100; } // Please Hire Me ;) function playGame(uint256 difficultyLevel,uint256 breakInStyle,uint256 scenario) public returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"No Character Deposited"); require(NFTCharacterDepositLedger[msg.sender].arrested == false,"Character in Prison"); require(scenario < differentGameScenarios, "No Game Scenario"); bytes32 requestID = requestRandomness(keyHash, fee); currentGameMode[requestID].gameMode = 0; currentGamePlays[requestID].player = msg.sender; currentGamePlays[requestID].breakInStyle = breakInStyle; currentGamePlays[requestID].difficultyLevel = difficultyLevel; currentGamePlays[requestID].scenario = scenario; currentGamePlays[requestID].agility = NFTCharacterDepositLedger[msg.sender].agility; currentGamePlays[requestID].strength = NFTCharacterDepositLedger[msg.sender].strength; currentGamePlays[requestID].charm = NFTCharacterDepositLedger[msg.sender].charm; currentGamePlays[requestID].sneak = NFTCharacterDepositLedger[msg.sender].sneak; currentGamePlays[requestID].health = NFTCharacterDepositLedger[msg.sender].health; return requestID; } function playBreakOut(uint256 breakInStyle, address targetPlayer) public returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); require(NFTCharacterDepositLedger[targetPlayer].isDeposited == true,"No Target Character Deposited"); require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"You have no Character Deposited"); require(NFTCharacterDepositLedger[targetPlayer].arrested == true,"Character is not in Prison"); require(targetPlayer != msg.sender,"You cannot free yourself"); bytes32 requestID = requestRandomness(keyHash, fee); currentGameMode[requestID].gameMode = 1; currentJailBreaks[requestID].player = msg.sender; currentJailBreaks[requestID].breakInStyle = breakInStyle; currentJailBreaks[requestID].targetPlayer = targetPlayer; currentJailBreaks[requestID].agility = NFTCharacterDepositLedger[msg.sender].agility; currentJailBreaks[requestID].strength = NFTCharacterDepositLedger[msg.sender].strength; currentJailBreaks[requestID].charm = NFTCharacterDepositLedger[msg.sender].charm; currentJailBreaks[requestID].sneak = NFTCharacterDepositLedger[msg.sender].sneak; currentJailBreaks[requestID].health = NFTCharacterDepositLedger[msg.sender].health; return requestID; } function playPVP(uint256 breakInStyle, address targetPlayer) public returns (bytes32) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); require(NFTCharacterDepositLedger[targetPlayer].isDeposited == true,"No Target Character Deposited"); require(NFTCharacterDepositLedger[msg.sender].isDeposited == true,"You have no Character Deposited"); require(targetPlayer != msg.sender,"You cannot rob from yourself"); require(NFTCharacterDepositLedger[msg.sender].lootingTimeout < block.timestamp); // only successfully rob someone once a day require(NFTCharacterDepositLedger[targetPlayer].lootingTimeout < block.timestamp); // only get robbed once a day require(jewelDepositLedger[targetPlayer] > (1*10**18)); // require targetPlayer has at least 1 jewel to prevent division issues. require(jewelDepositLedger[msg.sender] > (jewelDepositLedger[targetPlayer] / 2)); // you need to have at least 50% jewels of your target character to prvent small characters constantly attacking bytes32 requestID = requestRandomness(keyHash, fee); currentGameMode[requestID].gameMode = 2; currentPVPGamePlays[requestID].player = msg.sender; currentPVPGamePlays[requestID].breakInStyle = breakInStyle; currentPVPGamePlays[requestID].targetPlayer = targetPlayer; currentPVPGamePlays[requestID].agility = NFTCharacterDepositLedger[msg.sender].agility; currentPVPGamePlays[requestID].strength = NFTCharacterDepositLedger[msg.sender].strength; currentPVPGamePlays[requestID].charm = NFTCharacterDepositLedger[msg.sender].charm; currentPVPGamePlays[requestID].sneak = NFTCharacterDepositLedger[msg.sender].sneak; currentPVPGamePlays[requestID].health = NFTCharacterDepositLedger[msg.sender].health; currentPVPGamePlays[requestID].targetPlayerAgility = NFTCharacterDepositLedger[targetPlayer].agility; currentPVPGamePlays[requestID].targetPlayerStrength = NFTCharacterDepositLedger[targetPlayer].strength; currentPVPGamePlays[requestID].targetPlayerCharm = NFTCharacterDepositLedger[targetPlayer].charm; currentPVPGamePlays[requestID].targetPlayerSneak = NFTCharacterDepositLedger[targetPlayer].sneak; currentPVPGamePlays[requestID].targetPlayerHealth = NFTCharacterDepositLedger[targetPlayer].health; return requestID; } function vrfPlayGame(uint256 randomness, bytes32 requestId) internal { // only when randomness is returned can this function be called. if ((randomness % 2000) == 1 ){ // 1 in 2000 chance character dies NFTCharacterDepositLedger[currentGamePlays[requestId].player].isDeposited = false; emit gameCode(requestId, currentGamePlays[requestId].player,0); return; } if (((randomness % 143456) % 20) == 1 ){ // 1 in 20 chance character is injured uint256 healthDecrease = ((randomness % 123456) % 99); // player can lose up to 99 health every 1 in 20 if ((100-currentGamePlays[requestId].health+healthDecrease) > 100){ // players don't have to heal if they get injured before but if they get injured again and its greater than 100, they die NFTCharacterDepositLedger[currentGamePlays[requestId].player].isDeposited = false; emit gameCode(requestId,currentGamePlays[requestId].player,0); return; } NFTCharacterDepositLedger[currentGamePlays[requestId].player].health -= healthDecrease; emit gameCode(requestId,currentGamePlays[requestId].player,1); return; } if (((randomness % 23015) % 20) == 1 ){ // 1 in 20 chance character is almost getting arrested uint256 agilityRequiredtoEscape = ((randomness % 54321) % 1000); // player still has chance to escape if (currentGamePlays[requestId].agility > agilityRequiredtoEscape){ if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentGamePlays[requestId].player].agility += 1; } emit gameCode(requestId,currentGamePlays[requestId].player,3); return; // escaped but no money given } else{ NFTCharacterDepositLedger[currentGamePlays[requestId].player].arrested = true; NFTCharacterDepositLedger[currentGamePlays[requestId].player].freetoPlayAgain = block.timestamp + 172800; //player arrested for 2 days. emit gameCode(requestId,currentGamePlays[requestId].player,2); return; // playerArrested } } if (currentGamePlays[requestId].breakInStyle == 0){ //player is sneaking in uint256 sneakInExperienceRequired = ((randomness % 235674) % 750) + currentGamePlays[requestId].difficultyLevel+gameScenarios[currentGamePlays[requestId].scenario].riskBaseDifficulty; // difficulty will be somewhere between 0 to 10000 pluse the difficulty level which will be about 100 to 950 if (currentGamePlays[requestId].sneak > sneakInExperienceRequired) { uint256 totalWon = currentGamePlays[requestId].difficultyLevel*gameScenarios[currentGamePlays[requestId].scenario].payoutAmountBase; jewelDepositLedger[currentGamePlays[requestId].player] += totalWon; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentGamePlays[requestId].player].sneak += 1; } emit gameCode(requestId,currentGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentGamePlays[requestId].player,4); return; } if (currentGamePlays[requestId].breakInStyle == 1){ // player is breaking in with charm uint256 charmInExperienceRequired = ((randomness % 453678) % 750) + currentGamePlays[requestId].difficultyLevel+gameScenarios[currentGamePlays[requestId].scenario].riskBaseDifficulty; if (currentGamePlays[requestId].charm > charmInExperienceRequired) { uint256 totalWon = currentGamePlays[requestId].difficultyLevel*gameScenarios[currentGamePlays[requestId].scenario].payoutAmountBase; jewelDepositLedger[currentGamePlays[requestId].player] += totalWon; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentGamePlays[requestId].player].charm += 1; } emit gameCode(requestId,currentGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentGamePlays[requestId].player,4); return; } if (currentGamePlays[requestId].breakInStyle == 2){ // player is breaking in with strength uint256 strengthInExperienceRequired = ((randomness % 786435) % 750) + currentGamePlays[requestId].difficultyLevel+gameScenarios[currentGamePlays[requestId].scenario].riskBaseDifficulty; // strength is used for daylight robbery if (currentGamePlays[requestId].strength > strengthInExperienceRequired) { uint256 totalWon = currentGamePlays[requestId].difficultyLevel*gameScenarios[currentGamePlays[requestId].scenario].payoutAmountBase; jewelDepositLedger[currentGamePlays[requestId].player] += totalWon; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentGamePlays[requestId].player].strength += 1; } emit gameCode(requestId,currentGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentGamePlays[requestId].player,4); return; } } function vrfJailBreak(uint256 randomness, bytes32 requestId) internal { // only when randomness is returned can this function be called. if ((randomness % 1000) == 1 ){ // 5x higher chance of dying because its a jail // 1 in 1000 chance character dies NFTCharacterDepositLedger[currentJailBreaks[requestId].player].isDeposited = false; // emit gameCode(requestId, currentJailBreaks[requestId].player,0); return; } if (((randomness % 143456) % 10) == 1 ){ //2x higher chance of getting injured // 1 in 100 chance character is injured uint256 healthDecrease = ((randomness % 123456) % 99); // player can lose up to 99 health every 1 in 100 if ((100-currentJailBreaks[requestId].health+healthDecrease) > 100){ // players don't have to heal if they get injured before but if they get injured again and its greater than 100, they die NFTCharacterDepositLedger[msg.sender].isDeposited = false; // emit gameCode(requestId,currentJailBreaks[requestId].player,0); return; } NFTCharacterDepositLedger[currentJailBreaks[requestId].player].health -= healthDecrease; emit gameCode(requestId,currentJailBreaks[requestId].player,1); return; } if (((randomness % 23015) % 5) == 1 ){ // really high chance of getting spotted // 1 in 5 chance character is almost getting arrested uint256 agilityRequiredtoEscape = ((randomness % 54321) % 1000); // player still has chance to escape if (currentJailBreaks[requestId].agility > agilityRequiredtoEscape){ if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentJailBreaks[requestId].player].agility += 1; } emit gameCode(requestId,currentJailBreaks[requestId].player,3); return; // escaped but no money given } else{ NFTCharacterDepositLedger[msg.sender].arrested = true; NFTCharacterDepositLedger[msg.sender].freetoPlayAgain = block.timestamp + 259200; //player arrested for 3 days. emit gameCode(requestId,currentJailBreaks[requestId].player,2); return; // playerArrested } } if (currentJailBreaks[requestId].breakInStyle == 0){ //player is sneaking in uint256 sneakInExperienceRequired = ((randomness % 235674) % 1000); // difficulty will be somewhere between 0 to 10000 if (currentJailBreaks[requestId].sneak > sneakInExperienceRequired) { NFTCharacterDepositLedger[currentJailBreaks[requestId].targetPlayer].arrested = false; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentJailBreaks[requestId].player].sneak += 1; } emit gameCode(requestId,currentJailBreaks[requestId].targetPlayer,5); return; } emit gameCode(requestId,currentJailBreaks[requestId].player,4); return; } if (currentJailBreaks[requestId].breakInStyle == 1){ // player is breaking in with charm uint256 charmInExperienceRequired = ((randomness % 453678) % 1000); if (currentJailBreaks[requestId].charm > charmInExperienceRequired) { NFTCharacterDepositLedger[currentJailBreaks[requestId].targetPlayer].arrested = false; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentJailBreaks[requestId].player].charm += 1; } emit gameCode(requestId,currentJailBreaks[requestId].targetPlayer,5); return; } emit gameCode(requestId,currentJailBreaks[requestId].player,4); return; } if (currentJailBreaks[requestId].breakInStyle == 2){ // player is breaking in with strength uint256 strengthInExperienceRequired = ((randomness % 786435) % 1000); if (currentJailBreaks[requestId].strength > strengthInExperienceRequired) { NFTCharacterDepositLedger[currentJailBreaks[requestId].targetPlayer].arrested = false; if (((randomness % 2214) % 4) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentJailBreaks[requestId].player].strength += 1; } emit gameCode(requestId,currentJailBreaks[requestId].targetPlayer,5); return; } emit gameCode(requestId,currentJailBreaks[requestId].player,4); return; } } function vrfPlayPVP(uint256 randomness, bytes32 requestId) internal { // only when randomness is returned can this function be called. if ((randomness % 100) == 1 ){ // really high chance of getting killed // 1 in 100 chance character dies NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].isDeposited = false; // emit gameCode(requestId,currentPVPGamePlays[requestId].player,0); return; } if (((randomness % 143456) % 11) == 3 ){ //really high chance of getting injured // 1 in 11 chance character is injured uint256 healthDecrease = ((randomness % 123456) % 99); // player can lose up to 99 health every 1 in 100 if ((100-currentPVPGamePlays[requestId].health+healthDecrease) > 100){ // players don't have to heal if they get injured before but if they get injured again and its greater than 100, they die NFTCharacterDepositLedger[msg.sender].isDeposited = false; // emit gameCode(requestId,currentPVPGamePlays[requestId].player,0); return; } NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].health -= healthDecrease; emit gameCode(requestId,currentPVPGamePlays[requestId].player,1); return; } // no chance of getting arrested since you are a robbing another player // There is nothing stopping players with 800 sneak targeting players with 300 sneak. // It is assumed that the 800 sneak character will be more vulnerbale to strength attacks. // Players have to decide if they want to play more defensivly by equally levelling up each trait // or focus on one specfic trait which allows them to attack better but have worse defense. // Oh and please hire me. if (currentPVPGamePlays[requestId].breakInStyle == 0){ //player is sneaking in uint256 sneakInExperienceRequired = ((randomness % 235674) % 1000)+currentPVPGamePlays[requestId].targetPlayerSneak; // difficulty will be somewhere between 0 to 10000 plus the difficulty level which will be about 100 to 950 if (currentPVPGamePlays[requestId].sneak > sneakInExperienceRequired) { uint256 totalWon = jewelDepositLedger[currentPVPGamePlays[requestId].targetPlayer] / 20; // player can only lose 5% max each day if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].sneak += 1; } jewelDepositLedger[currentPVPGamePlays[requestId].targetPlayer] -= totalWon; jewelDepositLedger[currentPVPGamePlays[requestId].player] += totalWon; NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].lootingTimeout = block.timestamp + 86400; // players can only loot once a day NFTCharacterDepositLedger[currentPVPGamePlays[requestId].targetPlayer].lootingTimeout = block.timestamp + 86400; // players can only get looted once a day emit gameCode(requestId,currentPVPGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentPVPGamePlays[requestId].player,4); return; } if (currentPVPGamePlays[requestId].breakInStyle == 1){ // player is breaking in with charm uint256 charmInExperienceRequired = ((randomness % 453678) % 1000)+currentPVPGamePlays[requestId].targetPlayerCharm; if (currentPVPGamePlays[requestId].charm > charmInExperienceRequired) { uint256 totalWon = jewelDepositLedger[currentPVPGamePlays[requestId].targetPlayer] / 20; if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].charm += 1; } jewelDepositLedger[currentPVPGamePlays[requestId].player] += totalWon; NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].lootingTimeout = block.timestamp + 86400; // players can only loot once a day NFTCharacterDepositLedger[currentPVPGamePlays[requestId].targetPlayer].lootingTimeout = block.timestamp + 86400; // players can only get looted once a day emit gameCode(requestId,currentPVPGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentPVPGamePlays[requestId].player,4); return; } if (currentPVPGamePlays[requestId].breakInStyle == 2){ // player is breaking in with strength uint256 strengthInExperienceRequired = ((randomness % 786435) % 1000)+currentPVPGamePlays[requestId].targetPlayerStrength; // strength is used for daylight robbery if (currentPVPGamePlays[requestId].strength > strengthInExperienceRequired) { uint256 totalWon = jewelDepositLedger[currentPVPGamePlays[requestId].targetPlayer] / 20 ; // player can only lose 5% max each day if (((randomness % 2214) % 2) == 1 ){ // gain XP! NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].strength += 1; } jewelDepositLedger[currentPVPGamePlays[requestId].targetPlayer] -= totalWon; jewelDepositLedger[currentPVPGamePlays[requestId].player] += totalWon; NFTCharacterDepositLedger[currentPVPGamePlays[requestId].player].lootingTimeout = block.timestamp + 86400; // players can only loot once a day NFTCharacterDepositLedger[currentPVPGamePlays[requestId].targetPlayer].lootingTimeout = block.timestamp + 86400; // players can only get looted once a day emit gameCode(requestId,currentPVPGamePlays[requestId].player,totalWon); return; } emit gameCode(requestId,currentPVPGamePlays[requestId].player,4); return; } } function getRandomNumber() internal returns (bytes32 requestId) { // internal require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet"); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { if (currentGameMode[requestId].gameMode == 0){ vrfPlayGame(randomness,requestId); } if (currentGameMode[requestId].gameMode == 1){ vrfJailBreak(randomness,requestId); } if (currentGameMode[requestId].gameMode == 2){ vrfPlayPVP(randomness,requestId); } } function changeInheritance(address newInheritor) public onlyOwner { nextOwner = newInheritor; } function ownerCheckIn() public onlyOwner { lastCheckIn = block.timestamp; } function changeCheckInTime(uint256 newCheckInTimeInterval) public onlyOwner { checkInTimeInterval = newCheckInTimeInterval; // let owner change check in case he know he will be away for a while. } function passDownInheritance() internal { transferOwnership( nextOwner); } function checkUpkeep(bytes calldata /* checkData */) external view override returns (bool upkeepNeeded, bytes memory /* performData */) { return (block.timestamp > (lastCheckIn + checkInTimeInterval), bytes("")); // make sure to check in at least once every 6 months } function performUpkeep(bytes calldata /* performData */) onlyKeeper external override { passDownInheritance(); } function withdraw(uint amount) public onlyOwner returns(bool) { require(amount <= address(this).balance); payable(msg.sender).transfer(amount); //if the owner send to sender return true; } function withdrawErc20(IERC20 token) public onlyOwner{ require(token.transfer(msg.sender, token.balanceOf(address(this))), "Transfer failed"); } receive() external payable { // nothing to do but accept money } }
users Must Deposit a character to play
function depositNFT(uint256 NFTID) public {
5,535,036
./full_match/1/0x8787ca6A0aFffd8F634D09d7c2eE8D15b326e3f6/sources/src/FeeDistributor.sol
Return the user epoch number for `user` corresponding to the provided `timestamp`/ Perform binary search through epochs to find epoch containing `timestamp` Algorithm assumes that inputs are less than 2^128 so this operation is safe. +2 avoids getting stuck in min == mid < max max > min so this is safe.
function _findTimestampUserEpoch( address user, uint256 timestamp, uint256 minUserEpoch, uint256 maxUserEpoch ) internal view returns (uint256) { uint256 min = minUserEpoch; uint256 max = maxUserEpoch; for (uint256 i = 0; i < 128; ) { unchecked { if (min >= max) break; uint256 mid = (min + max + 2) / 2; IVotingEscrow.Point memory pt = _votingEscrow .user_point_history(user, mid); if (pt.ts <= timestamp) { min = mid; max = mid - 1; } } } return min; }
2,980,059
./full_match/1/0xd45a90376220237f18eF0B72F31d5683345566db/sources/contracts/msd/MSDControllerV2.sol
Ensure this is a MSD Controller contract./
function isMSDController() external pure returns (bool) { return true; }
4,985,706
./partial_match/57/0x2f09cbA262E39Bd18Dcfdaa1d59C284079Ac4093/sources/SYSLink.sol
Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
function transfer(address dst, uint256 rawAmount) external returns (bool) { uint96 amount = safe96( rawAmount, "SYSLink::transfer: amount exceeds 96 bits" ); _transferTokens(msg.sender, dst, amount); return true; }
16,909,796
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/AssetHelpers.sol"; import "./Moartroller.sol"; import "./SimplePriceOracle.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers { /** * @notice get the maximum asset value that can be still optimized. * @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value' * which is helpful to recalculate how much of this protection can be optimized again */ function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){ uint returnValue; uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments); uint totalProtectionLockedValue; (totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments); if(hypotheticalOptimizableValue <= totalProtectionLockedValue){ returnValue = 0; } else{ returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue); } return returnValue; } /** * @notice get the maximum value of an asset that can be optimized by protection for the given user * @dev optimizable = asset value * MPC * @return the hypothetical optimizable value * TODO: replace hardcoded 1e18 values */ function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) { uint assetValue = div_( mul_( div_( mul_( arguments.asset.balanceOf(arguments.account), arguments.asset.exchangeRateStored() ), 1e18 ), arguments.oracle.getUnderlyingPrice(arguments.asset) ), getAssetDecimalsMantissa(arguments.asset.getUnderlying()) ); uint256 hypotheticalOptimizableValue = div_( mul_( assetValue, arguments.asset.maxProtectionComposition() ), arguments.asset.maxProtectionCompositionMantissa() ); return hypotheticalOptimizableValue; } /** * @dev gets all locked protections values with mark to market value. Used by Moartroller. */ function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) { uint _lockedValue = 0; uint _markToMarket = 0; uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying()); for (uint j = 0; j < _protectionCount; j++) { uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j); bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId); if(protectionIsAlive){ _lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId)); uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset); uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId); if( assetSpotPrice > protectionStrikePrice) { _markToMarket = _markToMarket + div_( mul_( div_( mul_( assetSpotPrice - protectionStrikePrice, arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId) ), getAssetDecimalsMantissa(arguments.asset.underlying()) ), arguments.collateralFactorMantissa ), 1e18 ); } } } return (_lockedValue , _markToMarket); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "../MToken.sol"; import "../MProtection.sol"; import "../Interfaces/PriceOracle.sol"; interface LiquidityMathModelInterface { struct LiquidityMathArgumentsSet { MToken asset; address account; uint collateralFactorMantissa; MProtection cprotection; PriceOracle oracle; } function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint); function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint); function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Utils/ErrorReporter.sol"; import "./Utils/Exponential.sol"; import "./Interfaces/EIP20Interface.sol"; import "./MTokenStorage.sol"; import "./Interfaces/MTokenInterface.sol"; import "./Interfaces/MProxyInterface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; /** * @title MOAR's MToken Contract * @notice Abstract base for MTokens * @author MOAR */ abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage { /** * @notice Indicator that this is a MToken contract (for inspection) */ bool public constant isMToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when moartroller is changed */ event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Max protection composition value updated event */ event MpcUpdated(uint newValue); /** * @notice Initialize the money market * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function init(Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "not_admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "too_low"); // Set the moartroller uint err = _setMoartroller(moartroller_); require(err == uint(Error.NO_ERROR), "setting moartroller failed"); // Initialize block number and borrow index (block number mocks depend on moartroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; maxProtectionComposition = 5000; maxProtectionCompositionMantissa = 1e4; reserveFactorMaxMantissa = 1e18; borrowRateMaxMantissa = 0.0005e16; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srmTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srmTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // moartroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external virtual override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external virtual override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external virtual override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external virtual override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance_calculation_failed"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by moartroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) { uint mTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public virtual view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public virtual nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public virtual view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external virtual override view returns (uint) { return getCashPrior(); } function getRealBorrowIndex() public view returns (uint) { uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); Exp memory simpleInterestFactor; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor"); (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex"); return borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; AccrueInterestTempStorage memory temp; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = temp.borrowIndexNew; totalBorrows = temp.totalBorrowsNew; totalReserves = temp.totalReservesNew; if(temp.splitedReserves_2 > 0){ address mProxy = moartroller.mProxy(); EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2); MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2); } /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives mTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the mToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of mTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* * We calculate the new total supply of mTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming mTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems mTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) { require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing"); uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ //unused function // moartroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ /* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */ if (repayAmount == uint(-1)) { require(tx.origin == borrower, "specify a precise amount"); vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = mTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify mTokenCollateral market's block number equals current block number */ if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower); require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(mTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another mToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. * Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external virtual override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new moartroller for the market * @dev Admin function to set a new moartroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK); } Moartroller oldMoartroller = moartroller; // Ensure invoke moartroller.isMoartroller() returns true require(newMoartroller.isMoartroller(), "not_moartroller"); // Set market's moartroller to newMoartroller moartroller = newMoartroller; // Emit NewMoartroller(oldMoartroller, newMoartroller) emit NewMoartroller(oldMoartroller, newMoartroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } reserveSplitFactorMantissa = newReserveSplitFactorMantissa; return uint(Error.NO_ERROR); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModelInterface oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "not_interest_model"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /** * @notice Sets new value for max protection composition parameter * @param newMPC New value of MPC * @return uint 0=success, otherwise a failure */ function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); } /** * @notice Returns address of underlying token * @return address of underlying token */ function getUnderlying() external override view returns(address){ return underlying; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal virtual view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; contract MoartrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, MOARTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_PROTECTION_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, MOARTROLLER_REJECTION, MOARTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_MOARTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_MOARTROLLER_REJECTION, LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_MOARTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_MOARTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_MOARTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_MOARTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_MOARTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract LiquidityMathModelErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, PRICE_ERROR, SNAPSHOT_ERROR } enum FailureInfo { ORACLE_PRICE_CHECK_FAILED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../Interfaces/EIP20Interface.sol"; contract AssetHelpers { /** * @dev return asset decimals mantissa. Returns 1e18 if ETH */ function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){ uint assetDecimals = 1e18; if (assetAddress != address(0)) { EIP20Interface token = EIP20Interface(assetAddress); assetDecimals = 10 ** uint256(token.decimals()); } return assetDecimals; } } // SPDX-License-Identifier: BSD-3-Clause // Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/MoartrollerInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Interfaces/MProxyInterface.sol"; import "./MoartrollerStorage.sol"; import "./Governance/UnionGovernanceToken.sol"; import "./MProtection.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./LiquidityMathModelV1.sol"; import "./Utils/SafeEIP20.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title MOAR's Moartroller Contract * @author MOAR */ contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable { using SafeEIP20 for EIP20Interface; /// @notice Indicator that this is a Moartroller contract (for inspection) bool public constant isMoartroller = true; /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when protection is changed event NewCProtection(MProtection oldCProtection, MProtection newCProtection); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPausedMToken(MToken mToken, string action, bool pauseState); /// @notice Emitted when a new MOAR speed is calculated for a market event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed); /// @notice Emitted when a new MOAR speed is set for a contributor event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when MOAR is distributed to a supplier event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex); /// @notice Emitted when MOAR is distributed to a borrower event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when MOAR is granted by admin event MoarGranted(address recipient, uint amount); event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel); event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel); /// @notice The initial MOAR index for a market uint224 public constant moarInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // Custom initializer function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer { admin = msg.sender; liquidityMathModel = mathModel; liquidationModel = lqdModel; rewardClaimEnabled = false; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external override returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) { return uint(Error.MOARTROLLER_MISMATCH); } // Keep the flywheel moving updateMoarSupplyIndex(mTokenCollateral); distributeSupplierMoar(mTokenCollateral, borrower); distributeSupplierMoar(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, src); distributeSupplierMoar(mToken, dst); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; address _account = account; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals())); // Pre-compute a conversion factor from tokens -> dai (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // Protection value calculation sumCollateral += protectionValueLocked // Mark to market value calculation sumCollateral += markToMarketValue uint protectionValueLocked; uint markToMarketValue; (protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle)); if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) { vars.sumCollateral = 0; } else { vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor)); } vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked); vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); _account = account; } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Returns the value of possible optimization left for asset * @param asset The MToken address * @param account The owner of asset * @return The value of possible optimization */ function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getMaxOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } /** * @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset * @param asset The MToken address * @param account The owner of asset * @return The amount of hypothetical optimization */ function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getHypotheticalOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) { return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens( LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet( oracle, this, mTokenBorrowed, mTokenCollateral, actualRepayAmount, account, liquidationIncentiveMantissa ) ); } /** * @notice Returns the amount of a specific asset that is locked under all c-ops * @param asset The MToken address * @param account The owner of asset * @return The amount of asset locked under c-ops */ function getUserLockedAmount(MToken asset, address account) public override view returns(uint) { uint protectionLockedAmount; address currency = asset.underlying(); uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency); for (uint i = 0; i < numOfProtections; i++) { uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i); if(cprotection.isProtectionAlive(cProtectionId)){ protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId); } } return protectionLockedAmount; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the moartroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the moartroller PriceOracle oldOracle = oracle; // Set moartroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a new CProtection that is allowed to use as a collateral optimisation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setProtection(address newCProtection) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } MProtection oldCProtection = cprotection; cprotection = MProtection(newCProtection); // Emit NewPriceOracle(oldOracle, newOracle) emit NewCProtection(oldCProtection, cprotection); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // TODO: this check is temporary switched off. we can make exception for UNN later // Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // // // Check collateral factor <= 0.9 // Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); // if (lessThanExp(highLimit, newCollateralFactorExp)) { // return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); // } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } function _setRewardClaimEnabled(bool status) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); rewardClaimEnabled = status; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } mToken.isMToken(); // Sanity check to make sure its really a MToken // Note that isMoared is not in active use anymore markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0}); tokenAddressToMToken[address(mToken.underlying())] = mToken; _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == moartrollerImplementation; } /*** MOAR Distribution ***/ /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal { uint currentMoarSpeed = moarSpeeds[address(mToken)]; if (currentMoarSpeed != 0) { // note that MOAR speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarSupplyIndex(address(mToken)); updateMoarBorrowIndex(address(mToken), borrowIndex); } else if (moarSpeed != 0) { // Add the MOAR market Market storage market = markets[address(mToken)]; require(market.isListed == true, "MOAR market is not listed"); if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) { moarSupplyState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) { moarBorrowState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentMoarSpeed != moarSpeed) { moarSpeeds[address(mToken)] = moarSpeed; emit MoarSpeedUpdated(mToken, moarSpeed); } } /** * @notice Accrue MOAR to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMoarSupplyIndex(address mToken) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; uint supplySpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = MToken(mToken).totalSupply(); uint moarAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); moarSupplyState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue MOAR to the market by updating the borrow index * @param mToken The market whose borrow index to update */ function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; uint borrowSpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex); uint moarAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); moarBorrowState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate MOAR accrued by a supplier and possibly transfer it to them * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOAR to */ function distributeSupplierMoar(address mToken, address supplier) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]}); moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = moarInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = MToken(mToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta); moarAccrued[supplier] = supplierAccrued; emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate MOAR accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOAR to */ function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]}); moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta); moarAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate additional accrued MOAR for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint moarSpeed = moarContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && moarSpeed > 0) { uint newAccrued = mul_(deltaBlocks, moarSpeed); uint contributorAccrued = add_(moarAccrued[contributor], newAccrued); moarAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the MOAR accrued by holder in all markets * @param holder The address to claim MOAR for */ function claimMoarReward(address holder) public { return claimMoar(holder, allMarkets); } /** * @notice Claim all the MOAR accrued by holder in the specified markets * @param holder The address to claim MOAR for * @param mTokens The list of markets to claim MOAR in */ function claimMoar(address holder, MToken[] memory mTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimMoar(holders, mTokens, true, true); } /** * @notice Claim all MOAR accrued by the holders * @param holders The addresses to claim MOAR for * @param mTokens The list of markets to claim MOAR in * @param borrowers Whether or not to claim MOAR earned by borrowing * @param suppliers Whether or not to claim MOAR earned by supplying */ function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public { require(rewardClaimEnabled, "reward claim is disabled"); for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; require(markets[address(mToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarBorrowIndex(address(mToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerMoar(address(mToken), holders[j], borrowIndex); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } if (suppliers == true) { updateMoarSupplyIndex(address(mToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierMoar(address(mToken), holders[j]); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } } } /** * @notice Transfer MOAR to the user * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param user The address of the user to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer * @return The amount of MOAR which was NOT transferred to the user */ function grantMoarInternal(address user, uint amount) internal returns (uint) { EIP20Interface moar = EIP20Interface(getMoarAddress()); uint moarRemaining = moar.balanceOf(address(this)); if (amount > 0 && amount <= moarRemaining) { moar.approve(mProxy, amount); MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount); return 0; } return amount; } /*** MOAR Distribution Admin ***/ /** * @notice Transfer MOAR to the recipient * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param recipient The address of the recipient to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer */ function _grantMoar(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant MOAR"); uint amountLeft = grantMoarInternal(recipient, amount); require(amountLeft == 0, "insufficient MOAR for grant"); emit MoarGranted(recipient, amount); } /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function _setMoarSpeed(MToken mToken, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); setMoarSpeedInternal(mToken, moarSpeed); } /** * @notice Set MOAR speed for a single contributor * @param contributor The contributor whose MOAR speed to update * @param moarSpeed New MOAR speed for contributor */ function _setContributorMoarSpeed(address contributor, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); // note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (moarSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } moarContributorSpeeds[contributor] = moarSpeed; emit ContributorMoarSpeedUpdated(contributor, moarSpeed); } /** * @notice Set liquidity math model implementation * @param mathModel the math model implementation */ function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel; liquidityMathModel = mathModel; emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel)); } /** * @notice Set liquidation model implementation * @param newLiquidationModel the liquidation model implementation */ function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public { require(msg.sender == admin, "only admin can set liquidation model implementation"); LiquidationModelInterface oldLiquidationModel = liquidationModel; liquidationModel = newLiquidationModel; emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel)); } function _setMoarToken(address moarTokenAddress) public { require(msg.sender == admin, "only admin can set MOAR token address"); moarToken = moarTokenAddress; } function _setMProxy(address mProxyAddress) public { require(msg.sender == admin, "only admin can set MProxy address"); mProxy = mProxyAddress; } /** * @notice Add new privileged address * @param privilegedAddress address to add */ function _addPrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); privilegedAddresses[privilegedAddress] = 1; } /** * @notice Remove privileged address * @param privilegedAddress address to remove */ function _removePrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); delete privilegedAddresses[privilegedAddress]; } /** * @notice Check if address if privileged * @param privilegedAddress address to check */ function isPrivilegedAddress(address privilegedAddress) public view returns (bool) { return privilegedAddresses[privilegedAddress] == 1; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the MOAR token * @return The address of MOAR */ function getMoarAddress() public view returns (address) { return moarToken; } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/PriceOracle.sol"; import "./CErc20.sol"; /** * Temporary simple price feed */ contract SimplePriceOracle is PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(MToken mToken) public override view returns (uint) { if (compareStrings(mToken.symbol(), "mDAI")) { return 1e18; } else { return prices[address(MErc20(address(mToken)).underlying())]; } } function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public { address asset = address(MErc20(address(mToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 () internal { 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.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./Interfaces/CopMappingInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Moartroller.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/AssetHelpers.sol"; import "./MToken.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MProtection Contract * @notice Collateral optimization ERC-721 wrapper * @author MOAR */ contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; /** * @notice Event emitted when new MProtection token is minted */ event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime); /** * @notice Event emitted when MProtection token is redeemed */ event Redeem(address redeemer, uint tokenId, uint underlyingTokenId); /** * @notice Event emitted when MProtection token changes its locked value */ event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue); /** * @notice Event emitted when maturity window parameter is changed */ event MaturityWindowUpdated(uint newMaturityWindow); Counters.Counter private _tokenIds; address private _copMappingAddress; address private _moartrollerAddress; mapping (uint256 => uint256) private _underlyingProtectionTokensMapping; mapping (uint256 => uint256) private _underlyingProtectionLockedValue; mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping; uint256 public _maturityWindow; struct ProtectionMappedData{ address pool; address underlyingAsset; uint256 amount; uint256 strike; uint256 premium; uint256 lockedValue; uint256 totalValue; uint issueTime; uint expirationTime; bool isProtectionAlive; } /** * @notice Constructor for MProtection contract * @param copMappingAddress The address of data mapper for C-OP * @param moartrollerAddress The address of the Moartroller */ function initialize(address copMappingAddress, address moartrollerAddress) public initializer { __Ownable_init(); __ERC721_init("c-uUNN OC-Protection", "c-uUNN"); _copMappingAddress = copMappingAddress; _moartrollerAddress = moartrollerAddress; _setMaturityWindow(10800); // 3 hours default } /** * @notice Returns C-OP mapping contract */ function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); } /** * @notice Mint new MProtection token * @param underlyingTokenId Id of C-OP token that will be deposited * @return ID of minted MProtection token */ function mint(uint256 underlyingTokenId) public returns (uint256) { return mintFor(underlyingTokenId, msg.sender); } /** * @notice Mint new MProtection token for specified address * @param underlyingTokenId Id of C-OP token that will be deposited * @param receiver Address that will receive minted Mprotection token * @return ID of minted MProtection token */ function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256) { CopMappingInterface copMappingInstance = copMapping(); ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); addUProtectionIndexes(receiver, newItemId, underlyingTokenId); emit Mint( receiver, newItemId, underlyingTokenId, copMappingInstance.getUnderlyingAsset(underlyingTokenId), copMappingInstance.getUnderlyingAmount(underlyingTokenId), copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId), copMappingInstance.getUnderlyingDeadline(underlyingTokenId) ); return newItemId; } /** * @notice Redeem C-OP token * @param tokenId Id of MProtection token that will be withdrawn * @return ID of redeemed C-OP token */ function redeem(uint256 tokenId) external returns (uint256) { require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved"); uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId); removeProtectionIndexes(tokenId); _burn(tokenId); emit Redeem(msg.sender, tokenId, underlyingTokenId); return underlyingTokenId; } /** * @notice Returns set of C-OP data * @param tokenId Id of MProtection token * @return ProtectionMappedData struct filled with C-OP data */ function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){ ProtectionMappedData memory data; (address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId); data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId)); return data; } /** * @notice Returns underlying token ID * @param tokenId Id of MProtection token */ function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){ return _underlyingProtectionTokensMapping[tokenId]; } /** * @notice Returns size of C-OPs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].length(); } /** * @notice Returns list of C-OP IDs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].at(index); } /** * @notice Checks if address is owner of MProtection * @param owner Address of potential owner to check * @param tokenId ID of MProtection to check */ function isUserProtection(address owner, uint256 tokenId) public view returns(bool) { if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){ return true; } return owner == ownerOf(tokenId); } /** * @notice Checks if MProtection is stil alive * @param tokenId ID of MProtection to check */ function isProtectionAlive(uint256 tokenId) public view returns(bool) { uint256 deadline = getUnderlyingDeadline(tokenId); return (deadline - _maturityWindow) > now; } /** * @notice Creates appropriate indexes for C-OP * @param owner C-OP owner address * @param tokenId ID of MProtection * @param underlyingTokenId ID of C-OP */ function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{ address currency = copMapping().getUnderlyingAsset(underlyingTokenId); _underlyingProtectionTokensMapping[tokenId] = underlyingTokenId; _protectionCurrencyMapping[owner][currency].add(tokenId); } /** * @notice Remove indexes for C-OP * @param tokenId ID of MProtection */ function removeProtectionIndexes(uint256 tokenId) private{ address owner = ownerOf(tokenId); address currency = getUnderlyingAsset(tokenId); _underlyingProtectionTokensMapping[tokenId] = 0; _protectionCurrencyMapping[owner][currency].remove(tokenId); } /** * @notice Returns C-OP total value * @param tokenId ID of MProtection */ function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); return div_( mul_( getUnderlyingStrikePrice(tokenId), getUnderlyingAmount(tokenId) ), assetDecimalsMantissa ); } /** * @notice Returns C-OP locked value * @param tokenId ID of MProtection */ function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){ return _underlyingProtectionLockedValue[tokenId]; } /** * @notice get the amount of underlying asset that is locked * @param tokenId CProtection tokenId * @return amount locked */ function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); // calculates total protection value uint256 protectionValue = div_( mul_( getUnderlyingAmount(tokenId), getUnderlyingStrikePrice(tokenId) ), assetDecimalsMantissa ); // return value is lockedValue / totalValue * amount return div_( mul_( getUnderlyingAmount(tokenId), div_( mul_( _underlyingProtectionLockedValue[tokenId], 1e18 ), protectionValue ) ), 1e18 ); } /** * @notice Locks the given protection value as collateral optimization * @param tokenId The MProtection token id * @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization * @return locked protection value * TODO: convert semantic errors to standarized error codes */ function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) { //check if the protection belongs to the caller require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION"); address currency = getUnderlyingAsset(tokenId); Moartroller moartroller = Moartroller(_moartrollerAddress); MToken mToken = moartroller.tokenAddressToMToken(currency); require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE"); uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId); uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId)); // add protection locked value if any uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId); if ( protectionLockedValue > 0) { maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue); } uint valueToLock; if (value != 0) { // check if lock value is at most max optimizable value require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE"); // check if lock value is at most protection total value require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE"); valueToLock = value; } else { // if we want to lock maximum protection value let's lock the value that is at most max optimizable value if (protectionTotalValue > maxOptimizableValue) { valueToLock = maxOptimizableValue; } else { valueToLock = protectionTotalValue; } } _underlyingProtectionLockedValue[tokenId] = valueToLock; emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock); return valueToLock; } function _setCopMapping(address newMapping) public onlyOwner { _copMappingAddress = newMapping; } function _setMoartroller(address newMoartroller) public onlyOwner { _moartrollerAddress = newMoartroller; } function _setMaturityWindow(uint256 maturityWindow) public onlyOwner { emit MaturityWindowUpdated(maturityWindow); _maturityWindow = maturityWindow; } // MAPPINGS function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getProtectionData(underlyingTokenId); } function getUnderlyingAsset(uint256 tokenId) public view returns (address){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAsset(underlyingTokenId); } function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAmount(underlyingTokenId); } function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingStrikePrice(underlyingTokenId); } function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingDeadline(underlyingTokenId); } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface PriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(MToken mToken) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; abstract contract MTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @dev EIP-20 token name for this token */ string public name; /** * @dev EIP-20 token symbol for this token */ string public symbol; /** * @dev EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Underlying asset for this MToken */ address public underlying; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal borrowRateMaxMantissa; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal reserveFactorMaxMantissa; /** * @dev Administrator for this contract */ address payable public admin; /** * @dev Pending administrator for this contract */ address payable public pendingAdmin; /** * @dev Contract which oversees inter-mToken operations */ Moartroller public moartroller; /** * @dev Model which tells what the current interest rate should be */ AbstractInterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @dev Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @dev Fraction of reserves currently set aside for other usage */ uint public reserveSplitFactorMantissa; /** * @dev Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @dev Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @dev Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @dev Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @dev Total number of tokens in circulation */ uint public totalSupply; /** * @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000 */ uint public maxProtectionComposition; /** * @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5 */ uint public maxProtectionCompositionMantissa; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; struct ProtectionUsage { uint256 protectionValueUsed; } /** * @dev Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; mapping (uint256 => ProtectionUsage) protectionsUsed; } struct AccrueInterestTempStorage{ uint interestAccumulated; uint reservesAdded; uint splitedReserves_1; uint splitedReserves_2; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) public accountBorrows; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./EIP20Interface.sol"; interface MTokenInterface { /*** User contract ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function getUnderlying() external view returns(address); function sweepToken(EIP20Interface token) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface MProxyInterface { function proxyClaimReward(address asset, address recipient, uint amount) external; function proxySplitReserves(address asset, uint amount) external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/InterestRateModelInterface.sol"; abstract contract AbstractInterestRateModel is InterestRateModelInterface { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Careful Math * @author MOAR * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; import "../Utils/ExponentialNoError.sol"; interface MoartrollerInterface { /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; ExponentialNoError.Exp collateralFactor; ExponentialNoError.Exp exchangeRate; ExponentialNoError.Exp oraclePrice; ExponentialNoError.Exp tokensToDenom; } /*** Assets You Are In ***/ function enterMarkets(address[] calldata mTokens) external returns (uint[] memory); function exitMarket(address mToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeUserTokens( address mTokenBorrowed, address mTokenCollateral, uint repayAmount, address account) external view returns (uint, uint); function getUserLockedAmount(MToken asset, address account) external view returns(uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface Versionable { function getContractVersion() external pure returns (string memory); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "./MProtection.sol"; abstract contract UnitrollerAdminStorage { /** * @dev Administrator for this contract */ address public admin; /** * @dev Pending administrator for this contract */ address public pendingAdmin; /** * @dev Active brains of Unitroller */ address public moartrollerImplementation; /** * @dev Pending brains of Unitroller */ address public pendingMoartrollerImplementation; } contract MoartrollerV1Storage is UnitrollerAdminStorage { /** * @dev Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @dev Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @dev Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @dev Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => MToken[]) public accountAssets; } contract MoartrollerV2Storage is MoartrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives MOAR bool isMoared; } /** * @dev Official mapping of mTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @dev The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract MoartrollerV3Storage is MoartrollerV2Storage { struct MoarMarketState { // The market's last updated moarBorrowIndex or moarSupplyIndex uint224 index; // The block number the index was last updated at uint32 block; } /// @dev A list of all markets MToken[] public allMarkets; /// @dev The rate at which the flywheel distributes MOAR, per block uint public moarRate; /// @dev The portion of moarRate that each market currently receives mapping(address => uint) public moarSpeeds; /// @dev The MOAR market supply state for each market mapping(address => MoarMarketState) public moarSupplyState; /// @dev The MOAR market borrow state for each market mapping(address => MoarMarketState) public moarBorrowState; /// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarSupplierIndex; /// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarBorrowerIndex; /// @dev The MOAR accrued but not yet transferred to each user mapping(address => uint) public moarAccrued; } contract MoartrollerV4Storage is MoartrollerV3Storage { // @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract MoartrollerV5Storage is MoartrollerV4Storage { /// @dev The portion of MOAR that each contributor receives per block mapping(address => uint) public moarContributorSpeeds; /// @dev Last block at which a contributor's MOAR rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract MoartrollerV6Storage is MoartrollerV5Storage { /** * @dev Moar token address */ address public moarToken; /** * @dev MProxy address */ address public mProxy; /** * @dev CProtection contract which can be used for collateral optimisation */ MProtection public cprotection; /** * @dev Mapping for basic token address to mToken */ mapping(address => MToken) public tokenAddressToMToken; /** * @dev Math model for liquidity calculation */ LiquidityMathModelInterface public liquidityMathModel; /** * @dev Liquidation model for liquidation related functions */ LiquidationModelInterface public liquidationModel; /** * @dev List of addresses with privileged access */ mapping(address => uint) public privilegedAddresses; /** * @dev Determines if reward claim feature is enabled */ bool public rewardClaimEnabled; } // Copyright (c) 2020 The UNION Protocol Foundation // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @title UNION Protocol Governance Token * @dev Implementation of the basic standard token. */ contract UnionGovernanceToken is AccessControl, IERC20 { using Address for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /** * @notice Struct for marking number of votes from a given block * @member from * @member votes */ struct VotingCheckpoint { uint256 from; uint256 votes; } /** * @notice Struct for locked tokens * @member amount * @member releaseTime * @member votable */ struct LockedTokens{ uint amount; uint releaseTime; bool votable; } /** * @notice Struct for EIP712 Domain * @member name * @member version * @member chainId * @member verifyingContract * @member salt */ struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } /** * @notice Struct for EIP712 VotingDelegate call * @member owner * @member delegate * @member nonce * @member expirationTime */ struct VotingDelegate { address owner; address delegate; uint256 nonce; uint256 expirationTime; } /** * @notice Struct for EIP712 Permit call * @member owner * @member spender * @member value * @member nonce * @member deadline */ struct Permit { address owner; address spender; uint256 value; uint256 nonce; uint256 deadline; } /** * @notice Vote Delegation Events */ event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate); event VotingDelegateRemoved(address indexed _owner); /** * @notice Vote Balance Events * Emmitted when a delegate account's vote balance changes at the time of a written checkpoint */ event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance); /** * @notice Transfer/Allocator Events */ event TransferStatusChanged(bool _newTransferStatus); /** * @notice Reversion Events */ event ReversionStatusChanged(bool _newReversionSetting); /** * @notice EIP-20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice EIP-20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed _from, uint256 _value); event AddressPermitted(address indexed _account); event AddressRestricted(address indexed _account); /** * @dev AccessControl recognized roles */ bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE"); bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN"); bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT"); bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK"); bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED"); bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST"); bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( "DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)" ); //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; address private constant BURN_ADDRESS = address(0); address public UPGT_CONTRACT_ADDRESS; /** * @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting. */ bytes32 public immutable EIP712DOMAIN_SEPARATOR; /** * @dev EIP-20 token name */ string public name = "UNION Protocol Governance Token"; /** * @dev EIP-20 token symbol */ string public symbol = "UNN"; /** * @dev EIP-20 token decimals */ uint8 public decimals = 18; /** * @dev Contract version */ string public constant version = '0.0.1'; /** * @dev Initial amount of tokens */ uint256 private uint256_initialSupply = 100000000000 * 10**18; /** * @dev Total amount of tokens */ uint256 private uint256_totalSupply; /** * @dev Chain id */ uint256 private uint256_chain_id; /** * @dev general transfer restricted as function of public sale not complete */ bool private b_canTransfer = false; /** * @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions. */ bool private b_revert = false; //false allows false return values /** * @dev Locked destinations list */ mapping(address => bool) private m_lockedDestinations; /** * @dev EIP-20 allowance and balance maps */ mapping(address => mapping(address => uint256)) private m_allowances; mapping(address => uint256) private m_balances; mapping(address => LockedTokens[]) private m_lockedBalances; /** * @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712 */ mapping(address => uint256) private m_nonces; /** * @dev delegated account may for off-line vote delegation */ mapping(address => address) private m_delegatedAccounts; /** * @dev delegated account inverse map is needed to live calculate voting power */ mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap; /** * @dev indexed mapping of vote checkpoints for each account */ mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints; /** * @dev mapping of account addrresses to voting checkpoints */ mapping(address => uint256) private m_accountVotingCheckpoints; /** * @dev Contructor for the token * @param _owner address of token contract owner * @param _initialSupply of tokens generated by this contract * Sets Transfer the total suppply to the owner. * Sets default admin role to the owner. * Sets ROLE_ALLOCATE to the owner. * Sets ROLE_GOVERN to the owner. * Sets ROLE_MINT to the owner. * Sets EIP 712 Domain Separator. */ constructor(address _owner, uint256 _initialSupply) public { //set internal contract references UPGT_CONTRACT_ADDRESS = address(this); //setup roles using AccessControl _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLE_ADMIN, _owner); _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(ROLE_ALLOCATE, _owner); _setupRole(ROLE_ALLOCATE, _msgSender()); _setupRole(ROLE_TRUSTED, _owner); _setupRole(ROLE_TRUSTED, _msgSender()); _setupRole(ROLE_GOVERN, _owner); _setupRole(ROLE_MINT, _owner); _setupRole(ROLE_LOCK, _owner); _setupRole(ROLE_TEST, _owner); m_balances[_owner] = _initialSupply; uint256_totalSupply = _initialSupply; b_canTransfer = false; uint256_chain_id = _getChainId(); EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({ name : name, version : version, chainId : uint256_chain_id, verifyingContract : address(this), salt : keccak256(abi.encodePacked(name)) } )); emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply); } /** * @dev Sets transfer status to lock token transfer * @param _canTransfer value can be true or false. * disables transfer when set to false and enables transfer when true * Only a member of ADMIN role can call to change transfer status */ function setCanTransfer(bool _canTransfer) public { if(hasRole(ROLE_ADMIN, _msgSender())){ b_canTransfer = _canTransfer; emit TransferStatusChanged(_canTransfer); } } /** * @dev Gets status of token transfer lock * @return true or false status of whether the token can be transfered */ function getCanTransfer() public view returns (bool) { return b_canTransfer; } /** * @dev Sets transfer reversion status to either return false or throw on error * @param _reversion value can be true or false. * disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true * Only a member of ADMIN role can call to change transfer reversion status */ function setReversion(bool _reversion) public { if(hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TEST, _msgSender()) ) { b_revert = _reversion; emit ReversionStatusChanged(_reversion); } } /** * @dev Gets status of token transfer reversion * @return true or false status of whether the token transfer failures return false or are reverted */ function getReversion() public view returns (bool) { return b_revert; } /** * @dev retrieve current chain id * @return chain id */ function getChainId() public pure returns (uint256) { return _getChainId(); } /** * @dev Retrieve current chain id * @return chain id */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Retrieve total supply of tokens * @return uint256 total supply of tokens */ function totalSupply() public view override returns (uint256) { return uint256_totalSupply; } /** * Balance related functions */ /** * @dev Retrieve balance of a specified account * @param _account address of account holding balance * @return uint256 balance of the specified account address */ function balanceOf(address _account) public view override returns (uint256) { return m_balances[_account].add(_calculateReleasedBalance(_account)); } /** * @dev Retrieve locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); } /** * @dev Retrieve lenght of locked balance array for specific address * @param _account address of account holding locked balance * @return uint256 locked balance array lenght */ function getLockedTokensListSize(address _account) public view returns (uint256){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); return m_lockedBalances[_account].length; } /** * @dev Retrieve locked tokens struct from locked balance array for specific address * @param _account address of account holding locked tokens * @param _index index in array with locked tokens position * @return amount of locked tokens * @return releaseTime descibes time when tokens will be unlocked * @return votable flag is describing votability of tokens */ function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index"); LockedTokens storage lockedTokens = m_lockedBalances[_account][_index]; return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable); } /** * @dev Calculates locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function _calculateLockedBalance(address _account) private view returns (uint256) { uint256 lockedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime > block.timestamp){ lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount); } } return lockedBalance; } /** * @dev Calculates released balance of a specified account * @param _account address of account holding released balance * @return uint256 released balance of the specified account address */ function _calculateReleasedBalance(address _account) private view returns (uint256) { uint256 releasedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount); } } return releasedBalance; } /** * @dev Calculates locked votable balance of a specified account * @param _account address of account holding locked votable balance * @return uint256 locked votable balance of the specified account address */ function _calculateLockedVotableBalance(address _account) private view returns (uint256) { uint256 lockedVotableBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].votable == true){ lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount); } } return lockedVotableBalance; } /** * @dev Moves released balance to normal balance for a specified account * @param _account address of account holding released balance */ function _moveReleasedBalance(address _account) internal virtual{ uint256 releasedToMove = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount); m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1]; m_lockedBalances[_account].pop(); } } m_balances[_account] = m_balances[_account].add(releasedToMove); } /** * Allowance related functinons */ /** * @dev Retrieve the spending allowance for a token holder by a specified account * @param _owner Token account holder * @param _spender Account given allowance * @return uint256 allowance value */ function allowance(address _owner, address _spender) public override virtual view returns (uint256) { return m_allowances[_owner][_spender]; } /** * @dev Message sender approval to spend for a specified amount * @param _spender address of party approved to spend * @param _value amount of the approval * @return boolean success status * public wrapper for _approve, _owner is msg.sender */ function approve(address _spender, uint256 _value) public override returns (bool) { bool success = _approveUNN(_msgSender(), _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: APPROVE ERROR"); } return success; } /** * @dev Token owner approval of amount for specified spender * @param _owner address of party that owns the tokens being granted approval for spending * @param _spender address of party that is granted approval for spending * @param _value amount approved for spending * @return boolean approval status * if _spender allownace for a given _owner is greater than 0, * increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738 */ function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (m_allowances[_owner][_spender] == 0 || _value == 0) ){ m_allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); retval = true; } return retval; } /** * @dev Increase spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _addedValue specified incremental increase * @return boolean increaseAllowance status * public wrapper for _increaseAllowance, _owner restricted to msg.sender */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to increase spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _addedValue specified incremental increase * @return boolean return value status * increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address. */ function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _addedValue > 0 ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * @dev Decrease spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _subtractedValue specified incremental decrease * @return boolean success status * public wrapper for _decreaseAllowance, _owner restricted to msg.sender */ //public wrapper for _decreaseAllowance, _owner restricted to msg.sender function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue); if(!success && b_revert){ revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to decrease spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _subtractedValue specified incremental decrease * @return boolean return value status * decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address. */ function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _subtractedValue > 0 && m_allowances[_owner][_spender] >= _subtractedValue ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * LockedDestination related functions */ /** * @dev Adds address as a designated destination for tokens when locked for allocation only * @param _address Address of approved desitnation for movement during lock * @return success in setting address as eligible for transfer independent of token lock status */ function setAsEligibleLockedDestination(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ m_lockedDestinations[_address] = true; retVal = true; } return retVal; } /** * @dev removes desitnation as eligible for transfer * @param _address address being removed */ function removeEligibleLockedDestination(address _address) public { if(hasRole(ROLE_ADMIN, _msgSender())){ require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); delete(m_lockedDestinations[_address]); } } /** * @dev checks whether a destination is eligible as recipient of transfer independent of token lock status * @param _address address being checked * @return whether desitnation is locked */ function checkEligibleLockedDesination(address _address) public view returns (bool) { return m_lockedDestinations[_address]; } /** * @dev Adds address as a designated allocator that can move tokens when they are locked * @param _address Address receiving the role of ROLE_ALLOCATE * @return success as true or false */ function setAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ grantRole(ROLE_ALLOCATE, _address); retVal = true; } return retVal; } /** * @dev Removes address as a designated allocator that can move tokens when they are locked * @param _address Address being removed from the ROLE_ALLOCATE * @return success as true or false */ function removeAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ if(hasRole(ROLE_ALLOCATE, _address)){ revokeRole(ROLE_ALLOCATE, _address); retVal = true; } } return retVal; } /** * @dev Checks to see if an address has the role of being an allocator * @param _address Address being checked for ROLE_ALLOCATE * @return true or false whether the address has ROLE_ALLOCATE assigned */ function checkAsAllocator(address _address) public view returns (bool) { return hasRole(ROLE_ALLOCATE, _address); } /** * Transfer related functions */ /** * @dev Public wrapper for transfer function to move tokens of specified value to a given address * @param _to specified recipient * @param _value amount being transfered to recipient * @return status of transfer success */ function transfer(address _to, uint256 _value) external override returns (bool) { bool success = _transferUNN(_msgSender(), _to, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER"); } return success; } /** * @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required. * @param _owner The address owner where transfer originates * @param _to The address to transfer to * @param _value The amount to be transferred * @return status of transfer success */ function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_to] = m_balances[_to].add(_value); retval = true; //need to move voting delegates with transfer of tokens retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value to a given address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){ bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); retval = true; //need to move voting delegates with transfer of tokens // retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferFrom function * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; } /** * @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) { if( _spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_spender] = m_balances[_spender].add(_value); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer retval = retval && _moveVotingDelegates(_owner, _spender, _value); emit Transfer(_owner, _spender, _value); } } return retval; } /** * @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer // retval = retval && _moveVotingDelegates(_owner, _to, _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public function to burn tokens * @param _value number of tokens to be burned * @return whether tokens were burned * Only ROLE_MINTER may burn tokens */ function burn(uint256 _value) external returns (bool) { bool success = _burn(_value); if(!success && b_revert){ revert("UPGT_ERROR: FAILED TO BURN"); } return success; } /** * @dev Private function Burn tokens * @param _value number of tokens to be burned * @return bool whether the tokens were burned * only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet. */ function _burn(uint256 _value) internal returns (bool) { bool retval = false; if(hasRole(ROLE_MINT, _msgSender()) && (m_balances[_msgSender()] >= _value) ){ m_balances[_msgSender()] -= _value; uint256_totalSupply = uint256_totalSupply.sub(_value); retval = true; emit Burn(_msgSender(), _value); } return retval; } /** * Voting related functions */ /** * @dev Public wrapper for _calculateVotingPower function which calulates voting power * @dev voting power = balance + locked votable balance + delegations * @return uint256 voting power */ function calculateVotingPower() public view returns (uint256) { return _calculateVotingPower(_msgSender()); } /** * @dev Calulates voting power of specified address * @param _account address of token holder * @return uint256 voting power */ function _calculateVotingPower(address _account) private view returns (uint256) { uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account)); for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) { if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){ address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i); votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount)); } } return votingPower; } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful * Requires ROLE_TEST */ function moveVotingDelegates( address _source, address _destination, uint256 _amount) public returns (bool) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _moveVotingDelegates(_source, _destination, _amount); } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful */ function _moveVotingDelegates( address _source, address _destination, uint256 _amount ) internal returns (bool) { if(_source != _destination && _amount > 0) { if(_source != BURN_ADDRESS) { uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source]; uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0; if(sourceNumberOfVotingCheckpointsOriginal >= _amount) { uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount); _writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew); } } if(_destination != BURN_ADDRESS) { uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination]; uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0; uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount); _writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew); } } return true; } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Public function for writing voting checkpoint * Requires ROLE_TEST */ function writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) public { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); _writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes); } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Private function for writing voting checkpoint */ function _writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) internal { if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes; } else { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes); _numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1); } emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes); } /** * @dev Calculate account votes as of a specific block * @param _account address whose votes are counted * @param _blockNumber from which votes are being counted * @return number of votes counted */ function getVoteCountAtBlock( address _account, uint256 _blockNumber) public view returns (uint256) { uint256 voteCount = 0; if(_blockNumber < block.number) { if(m_accountVotingCheckpoints[_account] != 0) { if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) { voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes; } else if(m_votingCheckpoints[_account][0].from > _blockNumber) { voteCount = 0; } else { uint256 lower = 0; uint256 upper = m_accountVotingCheckpoints[_account].sub(1); while(upper > lower) { uint256 center = upper.sub((upper.sub(lower).div(2))); VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center]; if(votingCheckpoint.from == _blockNumber) { voteCount = votingCheckpoint.votes; break; } else if(votingCheckpoint.from < _blockNumber) { lower = center; } else { upper = center.sub(1); } } } } } return voteCount; } /** * @dev Vote Delegation Functions * @param _to address where message sender is assigning votes * @return success of message sender delegating vote * delegate function does not allow assignment to burn */ function delegateVote(address _to) public returns (bool) { return _delegateVote(_msgSender(), _to); } /** * @dev Delegate votes from token holder to another address * @param _from Token holder * @param _toDelegate Address that will be delegated to for purpose of voting * @return success as to whether delegation has been a success */ function _delegateVote( address _from, address _toDelegate) internal returns (bool) { bool retval = false; if(_toDelegate != BURN_ADDRESS) { address currentDelegate = m_delegatedAccounts[_from]; uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from)); address oldToDelegate = m_delegatedAccounts[_from]; m_delegatedAccounts[_from] = _toDelegate; m_delegatedAccountsInverseMap[oldToDelegate].remove(_from); if(_from != _toDelegate){ m_delegatedAccountsInverseMap[_toDelegate].add(_from); } retval = true; retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance); if(retval) { if(_from == _toDelegate){ emit VotingDelegateRemoved(_from); } else{ emit VotingDelegateChanged(_from, currentDelegate, _toDelegate); } } } return retval; } /** * @dev Revert voting delegate control to owner account * @param _account The account that has delegated its vote * @return success of reverting delegation to owner */ function _revertVotingDelegationToOwner(address _account) internal returns (bool) { return _delegateVote(_account, _account); } /** * @dev Used by an message sending account to recall its voting delegates * @return success of reverting delegation to owner */ function recallVotingDelegate() public returns (bool) { return _revertVotingDelegationToOwner(_msgSender()); } /** * @dev Retrieve the voting delegate for a specified account * @param _account The account that has delegated its vote */ function getVotingDelegate(address _account) public view returns (address) { return m_delegatedAccounts[_account]; } /** * EIP-712 related functions */ /** * @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit * @param _owner address of token owner * @param _spender address of designated spender * @param _value value permitted for spend * @param _deadline expiration of signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline)) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _approveUNN(_owner, _spender, _value); } /** * @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote * @param _owner address of token owner * @param _delegate address of voting delegate * @param _expiretimestamp expiration of delegation signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @ @return bool true or false depedening on whether vote was successfully delegated */ function delegateVoteBySignature( address _owner, address _delegate, uint256 _expiretimestamp, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, _hash(VotingDelegate( { owner : _owner, delegate : _delegate, nonce : m_nonces[_owner]++, expirationTime : _expiretimestamp }) ) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _delegateVote(_owner, _delegate); } /** * @dev Public hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain * Requires ROLE_TEST */ function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_eip712Domain); } /** * @dev Hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate * Requires ROLE_TEST */ function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_delegate); } /** * @dev Public hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit * Requires ROLE_TEST */ function hashPermit(Permit memory _permit) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_permit); } /** * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function * Requires ROLE_TEST */ function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _recoverSigner(_digest, _ecv, _ecr, _ecs); } /** * @dev Private hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain */ function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(_eip712Domain.name)), keccak256(bytes(_eip712Domain.version)), _eip712Domain.chainId, _eip712Domain.verifyingContract, _eip712Domain.salt ) ); } /** * @dev Private hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate */ function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) { return keccak256( abi.encode( DELEGATE_TYPEHASH, _delegate.owner, _delegate.delegate, _delegate.nonce, _delegate.expirationTime ) ); } /** * @dev Private hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit */ function _hash(Permit memory _permit) internal pure returns (bytes32) { return keccak256(abi.encode( PERMIT_TYPEHASH, _permit.owner, _permit.spender, _permit.value, _permit.nonce, _permit.deadline )); } /** * @dev Recover signer information from provided digest * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function */ function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(_digest, _ecv, _ecr, _ecs); require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../Interfaces/EIP20Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeEIP20 * @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. * This is a forked version of Openzeppelin's SafeERC20 contract but supporting * EIP20Interface instead of Openzeppelin's IERC20 * 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 SafeEIP20 { using SafeMath for uint256; using Address for address; function safeTransfer(EIP20Interface token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./MoartrollerInterface.sol"; pragma solidity ^0.6.12; interface LiquidationModelInterface { function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); struct LiquidateCalculateSeizeUserTokensArgumentsSet { PriceOracle oracle; MoartrollerInterface moartroller; address mTokenBorrowed; address mTokenCollateral; uint actualRepayAmount; address accountForLiquidation; uint liquidationIncentiveMantissa; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title MOAR's InterestRateModel Interface * @author MOAR */ interface InterestRateModelInterface { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev 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_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @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 _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @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 _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @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 || ERC721Upgradeable.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 _tokenOwners.contains(tokenId); } /** * @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 || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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"); // internal 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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface CopMappingInterface { function getTokenAddress() external view returns (address); function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint); function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address); function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256); function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint); function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.2 <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 pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // 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 pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract 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()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/MErc20Interface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MErc20 Contract * @notice MTokens which wrap an EIP-20 underlying */ contract MErc20 is MToken, MErc20Interface { using SafeEIP20 for EIP20Interface; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function init(address underlying_, Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // MToken initialize does the bulk of the work super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) { return borrowForInternal(borrower, borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower. * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param mTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral); return err; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20Interface token) override external { require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. *` * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20Interface token = EIP20Interface(underlying); uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); // Calculate the amount that was *actually* transferred uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { EIP20Interface token = EIP20Interface(underlying); token.safeTransfer(to, amount); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface MErc20Interface { /*** User contract ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function borrowFor(address payable borrower, uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); }
Public wrapper for transferFrom function _owner The address to transfer from _spender cannot be the burn address _value The amount to be transferred return status of transferFrom success _spender cannot be either this goverance token contract or burn/
function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; }
11,818,559
./full_match/44787/0x69c6059644de90bE598727431120467ee0acC5B4/sources/project_/contracts/KolorMarketplace.sol
/ get the current offset emissions of this land add offset
function addOffsetsEmmisionsOfLand( uint256 tokenId, uint256 emissions, address buyer ) public onlyAuthorized { totalOffsetsOfLand[tokenId]++; uint256 currentOffsetsOf = totalOffsetsOfLand[tokenId]; offsetsByLand[tokenId][currentOffsetsOf].vcuOffset = emissions; offsetsByLand[tokenId][currentOffsetsOf].offsetDate = block.timestamp; offsetsByLand[tokenId][currentOffsetsOf].tokenId = tokenId; offsetsByLand[tokenId][currentOffsetsOf].buyer = buyer; }
13,263,974
// File contracts/libraries/SafeMath.sol pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.7.5; /** * @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 contracts/mocks/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.7.5; /** * @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/interfaces/IERC1155.sol pragma solidity ^0.7.5; /** @title ERC-1155 Multi Token Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1155.md Note: The ERC-165 identifier for this interface is 0xd9b67a26. */ interface IERC1155 /* is ERC165 */ { /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_id` argument MUST be the token type being transferred. The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value); /** @dev Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard). The `_operator` argument MUST be msg.sender. The `_from` argument MUST be the address of the holder whose balance is decreased. The `_to` argument MUST be the address of the recipient whose balance is increased. The `_ids` argument MUST be the list of tokens being transferred. The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by. When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address). When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address). */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values); /** @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absense of an event assumes disabled). */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986. The URI MUST point a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". */ event URI(string _value, uint256 indexed _id); /** @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if balance of holder for token `_id` is lower than the `_value` sent. MUST revert on any other error. MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard). After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _id ID of the token type @param _value Transfer amount @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external; /** @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call). @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard). MUST revert if `_to` is the zero address. MUST revert if length of `_ids` is not the same as length of `_values`. MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient. MUST revert on any other error. MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard). Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc). After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard). @param _from Source address @param _to Target address @param _ids IDs of each token type (order and length must match _values array) @param _values Transfer amounts per token type (order and length must match _ids array) @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external; /** @notice Get the balance of an account's Tokens. @param _owner The address of the token holder @param _id ID of the Token @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** @notice Get the balance of multiple account/token pairs @param _owners The addresses of the token holders @param _ids ID of the Tokens @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens. @dev MUST emit the ApprovalForAll event on success. @param _operator Address to add to the set of authorized operators @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** @notice Queries the approval status of an operator for a given owner. @param _owner The owner of the Tokens @param _operator Address of authorized operator @return True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // File contracts/OP1155/IParagonBondingTreasury.sol pragma solidity 0.7.5; interface IParagonBondingTreasury { function sendPDT(uint _amountPayoutToken) external; function valueOfToken( address _principalToken, uint _amount ) external view returns ( uint value_ ); function PDT() external view returns (address); } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/OP1155/ParallelBondingContract.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; /// @title Parallel Bonding Contract /// @author JeffX /// @notice Bonding Parallel ERC1155s in return for PDT tokens contract ParallelBondingContract is Ownable { using SafeERC20 for IERC20; using SafeMath for uint; /// EVENTS /// /// @notice Emitted when A bond is created /// @param deposit Address of where bond is deposited to /// @param payout Amount of PDT to be paid out /// @param expires Block number bond will be fully redeemable event BondCreated( uint deposit, uint payout, uint expires ); /// @notice Emitted when a bond is redeemed /// @param recipient Address receiving PDT /// @param payout Amount of PDT redeemed /// @param remaining Amount of PDT left to be paid out event BondRedeemed( address recipient, uint payout, uint remaining ); /// STATE VARIABLES /// /// @notice Paragon DAO Token IERC20 immutable public PDT; /// @notice Parallel ERC1155 IERC1155 immutable public LL; /// @notice Custom Treasury IParagonBondingTreasury immutable public customTreasury; /// @notice Olympus DAO address address immutable public olympusDAO; /// @notice Olympus treasury address address public olympusTreasury; /// @notice Total Parallel tokens that have been bonded uint public totalPrincipalBonded; /// @notice Total PDT tokens given as payout uint public totalPayoutGiven; /// @notice Vesting term in blocks uint public vestingTerm; /// @notice Percent fee that goes to Olympus uint public immutable olympusFee = 33300; /// @notice Array of IDs that have been bondable uint[] public bondedIds; /// @notice Bool if bond contract has been initialized bool public initialized; /// @notice Stores bond information for depositors mapping( address => Bond ) public bondInfo; /// @notice Stores bond information for a Parallel ID mapping( uint => IdDetails ) public idDetails; /// STRUCTS /// /// @notice Details of an addresses current bond /// @param payout PDT tokens remaining to be paid /// @param vesting Blocks left to vest /// @param lastBlock Last interaction struct Bond { uint payout; uint vesting; uint lastBlock; } /// @notice Details of an ID that is to be bonded /// @param bondPrice Payout price of the ID /// @param remainingToBeSold Remaining amount of tokens that can be bonded /// @param inArray Bool if ID is in array that keeps track of IDs struct IdDetails { uint bondPrice; uint remainingToBeSold; bool inArray; } /// CONSTRUCTOR /// /// @param _customTreasury Address of cusotm treasury /// @param _LL Address of the Parallel token /// @param _olympusTreasury Address of the Olympus treasury /// @param _initialOwner Address of the initial owner /// @param _olympusDAO Address of Olympus DAO constructor( address _customTreasury, address _LL, address _olympusTreasury, address _initialOwner, address _olympusDAO ) { require( _customTreasury != address(0) ); customTreasury = IParagonBondingTreasury( _customTreasury ); PDT = IERC20( IParagonBondingTreasury(_customTreasury).PDT() ); require( _LL != address(0) ); LL = IERC1155( _LL ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; } /// POLICY FUNCTIONS /// /// @notice Initializes bond and sets vesting rate /// @param _vestingTerm Vesting term in blocks function initializeBond(uint _vestingTerm) external onlyPolicy() { require(!initialized, "Already initialized"); vestingTerm = _vestingTerm; initialized = true; } /// @notice Updates current vesting term /// @param _vesting New vesting in blocks function setVesting( uint _vesting ) external onlyPolicy() { require(initialized, "Not initalized"); vestingTerm = _vesting; } /// @notice Set bond price and how many to be sold for each ID /// @param _ids Array of IDs that will be sold /// @param _prices PDT given to bond correspond ID in `_ids` /// @param _toBeSold Number of IDs looking to be acquired function setIdDetails(uint[] calldata _ids, uint[] calldata _prices, uint _toBeSold) external onlyPolicy() { require(_ids.length == _prices.length, "Lengths do not match"); for(uint i; i < _ids.length; i++) { IdDetails memory idDetail = idDetails[_ids[i]]; idDetail.bondPrice = _prices[i]; idDetail.remainingToBeSold = _toBeSold; if(!idDetail.inArray) { bondedIds.push(_ids[i]); idDetail.inArray = true; } idDetails[_ids[i]] = idDetail; } } /// @notice Updates address to send Olympus fee to /// @param _olympusTreasury Address of new Olympus treasury function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /// USER FUNCTIONS /// /// @notice Bond Parallel ERC1155 to get PDT tokens /// @param _id ID number that is being bonded /// @param _amount Amount of sepcific `_id` to bond /// @param _depositor Address that PDT tokens will be redeemable for function deposit(uint _id, uint _amount, address _depositor) external returns (uint) { require(initialized, "Not initalized"); require( idDetails[_id].bondPrice > 0 && idDetails[_id].remainingToBeSold >= _amount, "Not bondable"); require( _amount > 0, "Cannot bond 0" ); require( _depositor != address(0), "Invalid address" ); uint payout; uint fee; (payout, fee) = payoutFor( _id ); // payout and fee is computed payout = payout.mul(_amount); fee = fee.mul(_amount); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: vestingTerm, lastBlock: block.number }); idDetails[_id].remainingToBeSold = idDetails[_id].remainingToBeSold.sub(_amount); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased customTreasury.sendPDT( payout.add(fee) ); PDT.safeTransfer(olympusTreasury, fee); LL.safeTransferFrom( msg.sender, address(customTreasury), _id, _amount, "" ); // transfer principal bonded to custom treasury // indexed events are emitted emit BondCreated( _id, payout, block.number.add( vestingTerm ) ); return payout; } /// @notice Redeem bond for `depositor` /// @param _depositor Address of depositor being redeemed /// @return Amount of PDT redeemed function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data PDT.safeTransfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); PDT.safeTransfer( _depositor, payout ); return payout; } } /// VIEW FUNCTIONS /// /// @notice Payout and fee for a specific bond ID /// @param _id ID to get payout and fee for /// @return payout_ Amount of PDT user will recieve for bonding `_id` /// @return fee_ Amount of PDT Olympus will recieve for the bonding of `_id` function payoutFor( uint _id ) public view returns ( uint payout_, uint fee_) { uint price = idDetails[_id].bondPrice; fee_ = price.mul( olympusFee ).div( 1e6 ); payout_ = price.sub(fee_); } /// @notice Calculate how far into vesting `_depositor` is /// @param _depositor Address of depositor /// @return percentVested_ Percent `_depositor` is into vesting function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /// @notice Calculate amount of payout token available for claim by `_depositor` /// @param _depositor Address of depositor /// @return pendingPayout_ Pending payout for `_depositor` function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /// @notice Returns all the ids that are bondable and the amounts that can be bonded for each /// @return Array of all IDs that are bondable /// @return Array of amount remaining to be bonded for each bondable ID function bondableIds() external view returns (uint[] memory, uint[] memory) { uint numberOfBondable; for(uint i = 0; i < bondedIds.length; i++) { uint id = bondedIds[i]; (bool active,) = canBeBonded(id); if(active) numberOfBondable++; } uint256[] memory ids = new uint256[](numberOfBondable); uint256[] memory leftToBond = new uint256[](numberOfBondable); uint nonce; for(uint i = 0; i < bondedIds.length; i++) { uint id = bondedIds[i]; (bool active, uint amount) = canBeBonded(id); if(active) { ids[nonce] = id; leftToBond[nonce] = amount; nonce++; } } return (ids, leftToBond); } /// @notice Determines if `_id` can be bonded, and if so how much is left /// @param _id ID to check if can be bonded /// @return Bool if `_id` can be bonded /// @return Amount of tokens that be bonded for `_id` function canBeBonded(uint _id) public view returns (bool, uint) { IdDetails memory idDetail = idDetails[_id]; if(idDetail.bondPrice > 0 && idDetail.remainingToBeSold > 0) { return (true, idDetail.remainingToBeSold); } else { return (false, 0); } } }
Returns all the ids that are bondable and the amounts that can be bonded for each return Array of all IDs that are bondable return Array of amount remaining to be bonded for each bondable ID
function bondableIds() external view returns (uint[] memory, uint[] memory) { uint numberOfBondable; for(uint i = 0; i < bondedIds.length; i++) { uint id = bondedIds[i]; (bool active,) = canBeBonded(id); if(active) numberOfBondable++; } uint256[] memory ids = new uint256[](numberOfBondable); uint256[] memory leftToBond = new uint256[](numberOfBondable); uint nonce; for(uint i = 0; i < bondedIds.length; i++) { uint id = bondedIds[i]; (bool active, uint amount) = canBeBonded(id); if(active) { ids[nonce] = id; leftToBond[nonce] = amount; nonce++; } } return (ids, leftToBond); for(uint i = 0; i < bondedIds.length; i++) { uint id = bondedIds[i]; (bool active, uint amount) = canBeBonded(id); if(active) { ids[nonce] = id; leftToBond[nonce] = amount; nonce++; } } return (ids, leftToBond); }
5,382,489
./full_match/11155111/0xFCc8a75ab4e55E1E9c3d8d1A8d833CB7BF45F5B7/sources/_ganache/console.log/console.sol
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution ```solidity uint256 count = 5; console.log('count: %d', count); console.log('count:', count); ``` See `util.format()` for more information./
function log(string memory value1, uint256 value2, bool value3, string memory value4) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint256,bool,string)", value1, value2, value3, value4)); }
3,821,443
./partial_match/1/0x5f3b3c37F47d8532836c800f75e7f262623Aa3BB/sources/JarvisAI.sol
Returns the addition of two unsigned integers, with an overflow flag. _Available since v3.4._/
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.0; 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); } }
15,662,723
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/lib/prb-math/src/sd59x18/Helpers.sol
Implements the unchecked modulo operation (%) in the SD59x18 type.
function mod(SD59x18 x, SD59x18 y) pure returns (SD59x18 result) { result = wrap(x.unwrap() % y.unwrap()); }
9,308,788
pragma solidity >= 0.4.24; pragma experimental ABIEncoderV2; /** @title Personal Journal. */ contract Journal { /* owner of Journal contract */ address owner; /* Author contains information about the author if he/she chooses to provide any public */ struct Author { string name; address authorAddress; } // Journal Entry at this point, keeping things simple and contain only plain-text struct JournalEntry { string [] title; string [] body; bool [] encrypt; string [] tags; } // Map of entries for a given Author mapping (address => Author) public authors; mapping (address => JournalEntry) internal entries; // Modifiers modifier verifyCaller(address _address) { require (msg.sender == _address); _; } // Events event AuthorInfoUpdated(address _address); event NewJournalEntryCreated(address _address); // Initialize the contract with the owner constructor() public { owner = msg.sender; } /** @dev Add author's name * @param _address address of the callee of the contract * @param _name name of the author provided */ //todo: hook up front-end to this function function addAuthorName(address _address, string memory _name) public verifyCaller(_address) { authors[_address].name = _name; emit AuthorInfoUpdated(_address); } /** @dev Get author's name * @param _address author's address * @return name Author's name */ function getAuthorName(address _address) public view verifyCaller(_address) returns(string memory name) { name = authors[_address].name; return name; } /** @dev Create Journal entry for an author * @param _title Journal Entry Title * @param _body Journal Entry main text * @param _encrypt Journal Entry boolean indicating whether to encrypt the post or not * @param _tags Journal Entry tags * @param _address Journal Entry author */ function createJournalEntry( string memory _title, string memory _body, bool _encrypt, string memory _tags, address _address) public verifyCaller(_address) { entries[_address].title.push(_title); entries[_address].body.push(_body); entries[_address].encrypt.push(_encrypt); entries[_address].tags.push(_tags); emit NewJournalEntryCreated(_address); } /** @dev Get the list of posts titles for a given user * @param _address Journal Entry author * @return title Journal Entry array Title */ function getJournalEntryTitle(address _address) public view returns (string[] memory) { return entries[_address].title; } /** @dev Get the list of maon body contexts for a given user * @param _address Journal Entry author * @return body Journal Entry array of main text */ function getJournalEntryBody(address _address) public view returns (string[] memory) { return entries[_address].body; } /** @dev Get the list of tags for a given user * @param _address Journal Entry author * @return tags Journal Entry array of tags */ function getJournalEntryTags(address _address) public view returns (string [] memory) { return entries[_address].tags; } /** @dev Get the list of encrypt booleans for a given user * @param _address Journal Entry author * @return tags Journal Entry array of encrypt flags */ function getJournalEntryEncryptFlags(address _address) public view returns (bool [] memory) { return entries[_address].encrypt; } /** @dev Get the list journal entries for a given user in one pass * @param _address Journal Entry author * @return title Journal Entry array Title * @return body Journal Entry array of main text * @return tags Journal Entry array of tags * @return tags Journal Entry array of encrypt flags */ function getJournalEntry(address _address) public view returns (string [] memory, string [] memory, string [] memory, bool [] memory) { return (entries[_address].title, entries[_address].body, entries[_address].tags, entries[_address].encrypt); } }
Get author's name _address author's address return name Author's name/
function getAuthorName(address _address) public view verifyCaller(_address) returns(string memory name) { name = authors[_address].name; return name; }
15,882,563
./full_match/43113/0x5bC445bbB32f75B9b09B68413d2042D3b87bEf8A/sources/lib/utils/StringUtils.sol
From provable-things Ethereum API : uint2Str
function intToString(uint v) public pure returns (string memory str) { if (tmp == 0) { return "0"; } uint j = tmp; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (tmp != 0) { bstr[k--] = byte(uint8(48 + tmp % 10)); tmp /= 10; } str = string(bstr); }
13,181,000
./full_match/42161/0xdCdE1d143A49B330fEa583199A63DE52e5D3bED7/sources/contracts/PepeDexPair.sol
force reserves to match balances
function sync() external lock { uint token0Balance = IERC20(token0).balanceOf(address(this)); uint token1Balance = IERC20(token1).balanceOf(address(this)); require(token0Balance != 0 && token1Balance != 0, "PepeDexPair: liquidity ratio not initialized"); _update(token0Balance, token1Balance); }
16,308,169
/** *Submitted for verification at Etherscan.io on 2022-01-24 */ /** *Submitted for verification at BscScan.com on 2022-01-06 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; 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; } } } /** * @dev Interface of the ETH165 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 ({ETH165Checker}). * * For an implementation, see {ETH165}. */ interface IETH165Upgradeable { /** * @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); } library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { 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; } } } /** * @dev Required interface of an ETH721 compliant contract. */ interface IETH721Upgradeable is IETH165Upgradeable { /** * @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 ETH721 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 {IETH721Receiver-onETH721Received}, 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 {IETH721Receiver-onETH721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ETH721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ETH721 asset contracts. */ interface IETH721ReceiverUpgradeable { /** * @dev Whenever an {IETH721} `tokenId` token is transferred to this contract via {IETH721-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 `IETH721.onETH721Received.selector`. */ function onETH721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ETH-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IETH721MetadataUpgradeable is IETH721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library 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); } } } } /* * @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; } /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdeg"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IETH165} interface. * * Contracts that want to implement ETH165 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, {ETH165Storage} provides an easier to use but more expensive implementation. */ abstract contract ETH165Upgradeable is Initializable, IETH165Upgradeable { function __ETH165_init() internal initializer { __ETH165_init_unchained(); } function __ETH165_init_unchained() internal initializer { } /** * @dev See {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IETH165Upgradeable).interfaceId; } uint256[50] private __gap; } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ETH721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ETH721Enumerable}. */ contract ETH721Upgradeable is Initializable, ContextUpgradeable, ETH165Upgradeable, IETH721Upgradeable, IETH721MetadataUpgradeable { 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(uint256 => mapping(address => uint256)) public 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 __ETH721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721_init_unchained(name_, symbol_); } function __ETH721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ETH165Upgradeable, IETH165Upgradeable) returns (bool) { return interfaceId == type(IETH721Upgradeable).interfaceId || interfaceId == type(IETH721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IETH721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ETH721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IETH721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ETH721: owner query for nonexistent token"); return owner; } /** * @dev See {IETH721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IETH721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IETH721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ETH721Metadata: 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 {IETH721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ETH721Upgradeable.ownerOf(tokenId); require(to != owner, "ETH721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ETH721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IETH721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ETH721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IETH721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ETH721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IETH721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IETH721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: transfer caller is not owner nor approved"); balances[tokenId][to] +=1; balances[tokenId][from] -=1; _transfer(from, to, tokenId); } /** * @dev See {IETH721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { balances[tokenId][to] +=1; balances[tokenId][from] -=1; safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IETH721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ETH721: 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 ETH721 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 {IETH721Receiver-onETH721Received}, 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(_checkOnETH721Received(from, to, tokenId, _data), "ETH721: transfer to non ETH721Receiver 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), "ETH721: operator query for nonexistent token"); address owner = ETH721Upgradeable.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 {IETH721Receiver-onETH721Received}, 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-ETH721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IETH721Receiver-onETH721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnETH721Received(address(0), to, tokenId, _data), "ETH721: transfer to non ETH721Receiver 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), "ETH721: mint to the zero address"); require(!_exists(tokenId), "ETH721: 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 = ETH721Upgradeable.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(ETH721Upgradeable.ownerOf(tokenId) == from, "ETH721: transfer of token that is not own"); require(to != address(0), "ETH721: 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(ETH721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IETH721Receiver-onETH721Received} 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 _checkOnETH721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IETH721ReceiverUpgradeable(to).onETH721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IETH721ReceiverUpgradeable.onETH721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ETH721: transfer to non ETH721Receiver 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; } /** * @title ETH-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IETH721EnumerableUpgradeable is IETH721Upgradeable { /** * @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); } /** * @dev This implements an optional extension of {ETH721} 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 ETH721EnumerableUpgradeable is Initializable, ETH721Upgradeable, IETH721EnumerableUpgradeable { function __ETH721Enumerable_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721Enumerable_init_unchained(); } function __ETH721Enumerable_init_unchained() internal initializer { } // 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 {IETH165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IETH165Upgradeable, ETH721Upgradeable) returns (bool) { return interfaceId == type(IETH721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IETH721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ETH721Upgradeable.balanceOf(owner), "ETH721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IETH721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IETH721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ETH721EnumerableUpgradeable.totalSupply(), "ETH721Enumerable: 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 = ETH721Upgradeable.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 = ETH721Upgradeable.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(); } uint256[46] private __gap; } /** * @dev ETH721 token with storage based token URI management. */ abstract contract ETH721URIStorageUpgradeable is Initializable, ETH721Upgradeable { function __ETH721URIStorage_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721URIStorage_init_unchained(); } function __ETH721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IETH721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ETH721Metadata: URI query for nonexistent token" ); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = super._baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ETH721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } uint256[49] private __gap; } /** * @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; } /** * @title ETH721 Burnable Token * @dev ETH721 Token that can be irreversibly burned (destroyed). */ abstract contract ETH721BurnableUpgradeable is Initializable, ContextUpgradeable, ETH721Upgradeable, OwnableUpgradeable { function __ETH721Burnable_init() internal initializer { __Context_init_unchained(); __ETH165_init_unchained(); __ETH721Burnable_init_unchained(); __Ownable_init(); } using SafeMathUpgradeable for uint256; function __ETH721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ETH721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length if( msg.sender == owner()){ address owner = ETH721Upgradeable.ownerOf(tokenId); balances[tokenId][owner].sub(1); _burn(tokenId); } else{ require(balances[tokenId][msg.sender] == 1,"Not a Owner"); balances[tokenId][msg.sender].sub(1); _burn(tokenId); } } uint256[50] private __gap; } interface IETH20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); /** * @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); } contract Milage721 is ETH721Upgradeable, ETH721EnumerableUpgradeable, ETH721URIStorageUpgradeable, ETH721BurnableUpgradeable { event Approve( address indexed owner, uint256 indexed token_id, bool approved ); event OrderPlace( address indexed from, uint256 indexed tokenId, uint256 indexed value ); event FeeTransfer( uint256 admin, uint256 creator, uint256 owner ); event CancelOrder(address indexed from, uint256 indexed tokenId); event ChangePrice(address indexed from, uint256 indexed tokenId, uint256 indexed value); event TokenId(address indexed from, uint256 indexed id); using SafeMathUpgradeable for uint256; struct Order { uint256 tokenId; uint256 price; } mapping(address => mapping(uint256 => Order)) public order_place; mapping(uint256 => mapping(address => bool)) public checkOrder; mapping (uint256 => uint256) public totalQuantity; mapping(uint256 => address) public _creator; mapping(uint256 => uint256) public _royal; mapping(string => address) private tokentype; uint256 private serviceValue; uint256 private sellervalue; string private _currentBaseURI; uint256 public _tid; uint256 deci; function initialize() public initializer { __Ownable_init(); ETH721Upgradeable.__ETH721_init("Milage trade center", "MILAGETECHLLC"); _tid = 1; serviceValue = 2500000000000000000; sellervalue = 0; deci = 18; } function getServiceFee() public view returns(uint256, uint256){ return (serviceValue, sellervalue); } function setServiceValue(uint256 _serviceValue, uint256 sellerfee) public onlyOwner{ serviceValue = _serviceValue; sellervalue = sellerfee; } function getTokenAddress(string memory _type) public view returns(address){ return tokentype[_type]; } function addTokenType(string[] memory _type,address[] memory tokenAddress) public onlyOwner{ require(_type.length == tokenAddress.length,"Not equal for type and tokenAddress"); for(uint i = 0; i < _type.length; i++) { tokentype[_type[i]] = tokenAddress[i]; } } function safeMint(address to, uint256 tokenId) public onlyOwner { _safeMint(to, tokenId); } function setBaseURI(string memory baseURI) public onlyOwner { _currentBaseURI = baseURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ETH721Upgradeable, ETH721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal override(ETH721Upgradeable, ETH721URIStorageUpgradeable) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view override(ETH721Upgradeable, ETH721URIStorageUpgradeable) returns (string memory) { return super.tokenURI(tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ETH721Upgradeable, ETH721EnumerableUpgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function mint( string memory ipfsmetadata, uint256 value, uint256 supply, uint256 royal ) public{ _tid = _tid.add(1); uint256 id_ = _tid.add(block.timestamp); _setTokenURI(id_, ipfsmetadata); _creator[id_]=msg.sender; _safeMint(msg.sender, id_); _royal[id_]=royal*1e18; balances[id_][msg.sender] =supply ; if (value != 0) { _orderPlace(msg.sender, id_, value); } totalQuantity[id_] = supply; emit TokenId(msg.sender, id_); } function orderPlace(uint256 tokenId, uint256 _price) public{ require(_price > 0, "Price must greater than Zero"); _orderPlace(msg.sender, tokenId, _price); } function _orderPlace( address from, uint256 tokenId, uint256 _price ) internal { require(balances[tokenId][from] > 0, "Is Not a Owner"); Order memory order; order.tokenId = tokenId; order.price = _price; order_place[from][tokenId] = order; checkOrder[tokenId][from] = true; emit OrderPlace(from, tokenId, _price); } function calc(uint256 amount, uint256 royal, uint256 _serviceValue, uint256 _sellervalue) internal pure returns(uint256, uint256, uint256){ uint256 fee = pETHent(amount, _serviceValue); uint256 roy = pETHent(amount, royal); uint256 netamount = 0; if(_sellervalue != 0){ uint256 fee1 = pETHent(amount, _sellervalue); fee = fee.add(fee1); netamount = amount.sub(fee1.add(roy)); } else{ netamount = amount.sub(roy); } return (fee, roy, netamount); } function pETHent(uint256 value1, uint256 value2) internal pure returns (uint256) { uint256 result = value1.mul(value2).div(1e20); return (result); } function saleWithToken(string memory tokenAss,address from , uint256 tokenId, uint256 amount) public{ newtokenasbid(tokenAss,from,amount,tokenId); if(checkOrder[tokenId][from]==true){ delete order_place[from][tokenId]; checkOrder[tokenId][from] = false; } tokenTrans(tokenId, from, msg.sender); } function newtokenasbid(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal { require( amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0, "Insufficent fund" ); uint256 val = pETHent(amount, serviceValue).add(amount); IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]); uint256 Tokendecimals = deci.sub(t.decimals()); uint256 approveValue = t.allowance(msg.sender, address(this)); require( approveValue >= val.div(10**Tokendecimals), "Insufficient approve"); require(balances[tokenId][from] > 0, "Is Not a Owner"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance"); if(_adminfee != 0){ t.transferFrom(msg.sender,owner(),_adminfee.div(10**Tokendecimals)); } if(roy != 0){ t.transferFrom(msg.sender,_creator[tokenId],roy.div(10**Tokendecimals)); } if(netamount != 0){ t.transferFrom(msg.sender,from,netamount.div(10**Tokendecimals)); } emit FeeTransfer(_adminfee,roy,netamount); } function _acceptBId(string memory tokenAss,address from, uint256 amount, uint256 tokenId) internal{ uint256 val = pETHent(amount, serviceValue).add(amount); IETH20Upgradeable t = IETH20Upgradeable(tokentype[tokenAss]); uint256 Tokendecimals = deci.sub(t.decimals()); uint256 approveValue = t.allowance(from, address(this)); require( approveValue >= val.div(10**Tokendecimals) && val > 0, "Insufficient approve"); require(balances[tokenId][msg.sender] > 0, "Is Not a Owner"); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( approveValue >= (_adminfee.add(roy.add(netamount))).div(10**Tokendecimals), "Insufficient approve balance"); if(_adminfee != 0){ t.transferFrom(from,owner(),_adminfee.div(10**Tokendecimals)); } if(roy != 0){ t.transferFrom(from,_creator[tokenId],roy.div(10**Tokendecimals)); } if(netamount != 0){ t.transferFrom(from,msg.sender,netamount.div(10**Tokendecimals)); } emit FeeTransfer(_adminfee,roy,netamount); } function saleToken( address payable from, uint256 tokenId, uint256 amount ) public payable { _saleToken(from, tokenId, amount); saleTokenTransfer(from, tokenId); } function _saleToken( address payable from, uint256 tokenId, uint256 amount ) internal { uint256 val = pETHent(amount, serviceValue).add(amount); require( msg.value == val, "msg.value Not equal to current amount"); require( amount == order_place[from][tokenId].price && order_place[from][tokenId].price > 0, "Insufficent fund" ); address payable create = payable(_creator[tokenId]); address payable admin = payable(owner()); (uint256 _adminfee, uint256 roy, uint256 netamount) = calc(amount, _royal[tokenId], serviceValue, sellervalue); require( msg.value == _adminfee.add(roy.add(netamount)), "msg.value Not equal to Calculation amount"); if(_adminfee != 0){ admin.transfer(_adminfee); } if(roy != 0){ create.transfer(roy); } if(netamount != 0){ from.transfer(netamount); } emit FeeTransfer(_adminfee,roy,netamount); } function saleTokenTransfer(address payable from, uint256 tokenId) internal { if (checkOrder[tokenId][from] == true) { delete order_place[from][tokenId]; checkOrder[tokenId][from] = false; } tokenTrans(tokenId, from, msg.sender); } function tokenTrans( uint256 tokenId, address from, address to ) internal { _approve(msg.sender,tokenId); safeTransferFrom(from, to, tokenId); } function acceptBId(string memory bidtoken,address bidaddr, uint256 amount, uint256 tokenId) public{ _acceptBId(bidtoken, bidaddr, amount, tokenId); if(checkOrder[tokenId][msg.sender]==true){ delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; } tokenTrans(tokenId,msg.sender, bidaddr); } function cancelOrder(uint256 tokenId) public{ require(balances[tokenId][msg.sender] > 0, "Is Not a Owner"); delete order_place[msg.sender][tokenId]; checkOrder[tokenId][msg.sender] = false; emit CancelOrder(msg.sender, tokenId); } function changePrice(uint256 value, uint256 tokenId) public{ require( balances[tokenId][msg.sender] > 0, "Is Not a Owner"); require( value < order_place[msg.sender][tokenId].price); order_place[msg.sender][tokenId].price = value; emit ChangePrice(msg.sender, tokenId, value); } function burnToken(uint256 id,address from) public{ require( balances[id][from] == 1, "You are Not a Token Owner or insufficient Token Balance"); burn(id); if(balances[id][from] == 1){ if(checkOrder[id][from]==true){ delete order_place[from][id]; checkOrder[id][from] = false; } } } }
ETH-721 Non-Fungible Token Standard, optional metadata extension/
interface IETH721MetadataUpgradeable is IETH721Upgradeable { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } }
5,998,886
./full_match/1/0x0De60C639Dd6EF4bA621C6D0b74548E403Ee74e5/sources/contracts/LotManager/V2/LotManagerV2LotsHandler.sol
Allow hegicStakingETH to spend allowance
function _buyETHLots(uint256 _ethLots) internal { token.approve(address(hegicStakingETH), 0); token.approve(address(hegicStakingETH), _ethLots * LOT_PRICE); hegicStakingETH.buy(_ethLots); emit ETHLotBought(_ethLots); }
8,417,876
./full_match/421613/0x1ce14D96e1f33eFC8844f30C8FC396e9c6b92cB0/sources/project_/contracts/BetaverseNFT.sol
A counter that keeps track of the number of tokens that have been minted.A mapping that stores the address of the miner and a boolean value.A variable that stores the base URI of the NFT.A modifier that checks if the function is queued in the TimeLock contract. If it is queued, it will execute the function and then remove it from the queue.
{ using Counters for Counters.Counter; bool public paused = false; Counters.Counter private _tokenIds; IBetaverseTimeLock TimeLockContract; mapping(address => bool) public isMiner; mapping(uint256 => address) private _minerOf; string private baseUri; event onMinerChange(address _miner, bool _isMiner); event onMint(address _miner, address _user, uint256 _tokenId); event onBaseURIChange(string _baseUri); modifier isQueued(string memory _functionName) pragma solidity ^0.8.0; { require(TimeLockContract.isQueuedTransaction(address(this), _functionName) == true, "INVALID_PERMISTION"); _; TimeLockContract.doneTransaction(_functionName); } modifier isEnableSystem() { require(paused == false, "SYSTEM_PAUSED"); _; } constructor( IBetaverseTimeLock _TimeLockContract, string memory _tokenName, string memory _tokenSymbol ) ERC721(_tokenName, _tokenSymbol) { TimeLockContract = _TimeLockContract; } function enableMiner(address _miner) public onlyOwner isQueued("enableMiner") { require(isMiner[_miner] == false, 'INVALID_MINER'); isMiner[_miner] = true; emit onMinerChange(_miner, true); } function disableMiner(address _miner) public onlyOwner isQueued("disableMiner") { require(isMiner[_miner] == true, 'INVALID_MINER'); isMiner[_miner] = false; emit onMinerChange(_miner, false); } function pauseSystem() public onlyOwner { paused = true; } function enableSystem() public onlyOwner { paused = false; } function setBaseURI(string memory _baseUri) public onlyOwner isQueued("setBaseURI") { require(bytes(_baseUri).length > 0, "wrong base uri"); baseUri = _baseUri; emit onBaseURIChange(_baseUri); } function mint(address to) public isEnableSystem returns(uint256) { require(isMiner[msg.sender] == true, "INVALID_MINER"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(to, newItemId); _minerOf[newItemId] = msg.sender; emit onMint(msg.sender, to, newItemId); return newItemId; } function burn(uint256 _tokenId) public isEnableSystem virtual { if (msg.sender != owner()) { require(_isApprovedOrOwner(msg.sender, _tokenId), "Burn caller is not owner nor approved"); } } function burn(uint256 _tokenId) public isEnableSystem virtual { if (msg.sender != owner()) { require(_isApprovedOrOwner(msg.sender, _tokenId), "Burn caller is not owner nor approved"); } } _burn(_tokenId); function minerOf(uint256 _tokenId) public view returns(address) { return _minerOf[_tokenId]; } function _baseURI() internal view override returns (string memory) { return baseUri; } }
11,573,159
/** Source code of Opium Protocol Web https://opium.network Telegram https://t.me/opium_network Twitter https://twitter.com/opium_network */ // File: LICENSE /** The software and documentation available in this repository (the "Software") is protected by copyright law and accessible pursuant to the license set forth below. Copyright © 2020 Blockeys BV. All rights reserved. Permission is hereby granted, free of charge, to any person or organization obtaining the Software (the “Licensee”) to privately study, review, and analyze the Software. Licensee shall not use the Software for any other purpose. Licensee shall not modify, transfer, assign, share, or sub-license the Software or any derivative works 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. */ // File: contracts/Lib/LibDerivative.sol pragma solidity 0.5.16; pragma experimental ABIEncoderV2; /// @title Opium.Lib.LibDerivative contract should be inherited by contracts that use Derivative structure and calculate derivativeHash contract LibDerivative { // Opium derivative structure (ticker) definition struct Derivative { // Margin parameter for syntheticId uint256 margin; // Maturity of derivative uint256 endTime; // Additional parameters for syntheticId uint256[] params; // oracleId of derivative address oracleId; // Margin token address of derivative address token; // syntheticId of derivative address syntheticId; } /// @notice Calculates hash of provided Derivative /// @param _derivative Derivative Instance of derivative to hash /// @return derivativeHash bytes32 Derivative hash function getDerivativeHash(Derivative memory _derivative) public pure returns (bytes32 derivativeHash) { derivativeHash = keccak256(abi.encodePacked( _derivative.margin, _derivative.endTime, _derivative.params, _derivative.oracleId, _derivative.token, _derivative.syntheticId )); } } // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * 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-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * IMPORTANT: It is unsafe to assume that an address for which this * function returns false is an externally-owned account (EOA) and not a * contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be 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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File: erc721o/contracts/Libs/LibPosition.sol pragma solidity ^0.5.4; library LibPosition { function getLongTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "LONG"))); } function getShortTokenId(bytes32 _hash) public pure returns (uint256 tokenId) { tokenId = uint256(keccak256(abi.encodePacked(_hash, "SHORT"))); } } // File: contracts/Interface/IDerivativeLogic.sol pragma solidity 0.5.16; /// @title Opium.Interface.IDerivativeLogic contract is an interface that every syntheticId should implement contract IDerivativeLogic is LibDerivative { /// @notice Validates ticker /// @param _derivative Derivative Instance of derivative to validate /// @return Returns boolean whether ticker is valid function validateInput(Derivative memory _derivative) public view returns (bool); /// @notice Calculates margin required for derivative creation /// @param _derivative Derivative Instance of derivative /// @return buyerMargin uint256 Margin needed from buyer (LONG position) /// @return sellerMargin uint256 Margin needed from seller (SHORT position) function getMargin(Derivative memory _derivative) public view returns (uint256 buyerMargin, uint256 sellerMargin); /// @notice Calculates payout for derivative execution /// @param _derivative Derivative Instance of derivative /// @param _result uint256 Data retrieved from oracleId on the maturity /// @return buyerPayout uint256 Payout in ratio for buyer (LONG position holder) /// @return sellerPayout uint256 Payout in ratio for seller (SHORT position holder) function getExecutionPayout(Derivative memory _derivative, uint256 _result) public view returns (uint256 buyerPayout, uint256 sellerPayout); /// @notice Returns syntheticId author address for Opium commissions /// @return authorAddress address The address of syntheticId address function getAuthorAddress() public view returns (address authorAddress); /// @notice Returns syntheticId author commission in base of COMMISSION_BASE /// @return commission uint256 Author commission function getAuthorCommission() public view returns (uint256 commission); /// @notice Returns whether thirdparty could execute on derivative's owner's behalf /// @param _derivativeOwner address Derivative owner address /// @return Returns boolean whether _derivativeOwner allowed third party execution function thirdpartyExecutionAllowed(address _derivativeOwner) public view returns (bool); /// @notice Returns whether syntheticId implements pool logic /// @return Returns whether syntheticId implements pool logic function isPool() public view returns (bool); /// @notice Sets whether thirds parties are allowed or not to execute derivative's on msg.sender's behalf /// @param _allow bool Flag for execution allowance function allowThirdpartyExecution(bool _allow) public; // Event with syntheticId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/Errors/CoreErrors.sol pragma solidity 0.5.16; contract CoreErrors { string constant internal ERROR_CORE_NOT_POOL = "CORE:NOT_POOL"; string constant internal ERROR_CORE_CANT_BE_POOL = "CORE:CANT_BE_POOL"; string constant internal ERROR_CORE_TICKER_WAS_CANCELLED = "CORE:TICKER_WAS_CANCELLED"; string constant internal ERROR_CORE_SYNTHETIC_VALIDATION_ERROR = "CORE:SYNTHETIC_VALIDATION_ERROR"; string constant internal ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE = "CORE:NOT_ENOUGH_TOKEN_ALLOWANCE"; string constant internal ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH = "CORE:TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH"; string constant internal ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED = "CORE:EXECUTION_BEFORE_MATURITY_NOT_ALLOWED"; string constant internal ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED = "CORE:SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED"; string constant internal ERROR_CORE_INSUFFICIENT_POOL_BALANCE = "CORE:INSUFFICIENT_POOL_BALANCE"; string constant internal ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID = "CORE:CANT_CANCEL_DUMMY_ORACLE_ID"; string constant internal ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED = "CORE:CANCELLATION_IS_NOT_ALLOWED"; string constant internal ERROR_CORE_UNKNOWN_POSITION_TYPE = "CORE:UNKNOWN_POSITION_TYPE"; } // File: contracts/Errors/RegistryErrors.sol pragma solidity 0.5.16; contract RegistryErrors { string constant internal ERROR_REGISTRY_ONLY_INITIALIZER = "REGISTRY:ONLY_INITIALIZER"; string constant internal ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED = "REGISTRY:ONLY_OPIUM_ADDRESS_ALLOWED"; string constant internal ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS = "REGISTRY:CANT_BE_ZERO_ADDRESS"; string constant internal ERROR_REGISTRY_ALREADY_SET = "REGISTRY:ALREADY_SET"; } // File: contracts/Registry.sol pragma solidity 0.5.16; /// @title Opium.Registry contract keeps addresses of deployed Opium contracts set to allow them route and communicate to each other contract Registry is RegistryErrors { // Address of Opium.TokenMinter contract address private minter; // Address of Opium.Core contract address private core; // Address of Opium.OracleAggregator contract address private oracleAggregator; // Address of Opium.SyntheticAggregator contract address private syntheticAggregator; // Address of Opium.TokenSpender contract address private tokenSpender; // Address of Opium commission receiver address private opiumAddress; // Address of Opium contract set deployer address public initializer; /// @notice This modifier restricts access to functions, which could be called only by initializer modifier onlyInitializer() { require(msg.sender == initializer, ERROR_REGISTRY_ONLY_INITIALIZER); _; } /// @notice Sets initializer constructor() public { initializer = msg.sender; } // SETTERS /// @notice Sets Opium.TokenMinter, Opium.Core, Opium.OracleAggregator, Opium.SyntheticAggregator, Opium.TokenSpender, Opium commission receiver addresses and allows to do it only once /// @param _minter address Address of Opium.TokenMinter /// @param _core address Address of Opium.Core /// @param _oracleAggregator address Address of Opium.OracleAggregator /// @param _syntheticAggregator address Address of Opium.SyntheticAggregator /// @param _tokenSpender address Address of Opium.TokenSpender /// @param _opiumAddress address Address of Opium commission receiver function init( address _minter, address _core, address _oracleAggregator, address _syntheticAggregator, address _tokenSpender, address _opiumAddress ) external onlyInitializer { require( minter == address(0) && core == address(0) && oracleAggregator == address(0) && syntheticAggregator == address(0) && tokenSpender == address(0) && opiumAddress == address(0), ERROR_REGISTRY_ALREADY_SET ); require( _minter != address(0) && _core != address(0) && _oracleAggregator != address(0) && _syntheticAggregator != address(0) && _tokenSpender != address(0) && _opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS ); minter = _minter; core = _core; oracleAggregator = _oracleAggregator; syntheticAggregator = _syntheticAggregator; tokenSpender = _tokenSpender; opiumAddress = _opiumAddress; } /// @notice Allows opium commission receiver address to change itself /// @param _opiumAddress address New opium commission receiver address function changeOpiumAddress(address _opiumAddress) external { require(opiumAddress == msg.sender, ERROR_REGISTRY_ONLY_OPIUM_ADDRESS_ALLOWED); require(_opiumAddress != address(0), ERROR_REGISTRY_CANT_BE_ZERO_ADDRESS); opiumAddress = _opiumAddress; } // GETTERS /// @notice Returns address of Opium.TokenMinter /// @param result address Address of Opium.TokenMinter function getMinter() external view returns (address result) { return minter; } /// @notice Returns address of Opium.Core /// @param result address Address of Opium.Core function getCore() external view returns (address result) { return core; } /// @notice Returns address of Opium.OracleAggregator /// @param result address Address of Opium.OracleAggregator function getOracleAggregator() external view returns (address result) { return oracleAggregator; } /// @notice Returns address of Opium.SyntheticAggregator /// @param result address Address of Opium.SyntheticAggregator function getSyntheticAggregator() external view returns (address result) { return syntheticAggregator; } /// @notice Returns address of Opium.TokenSpender /// @param result address Address of Opium.TokenSpender function getTokenSpender() external view returns (address result) { return tokenSpender; } /// @notice Returns address of Opium commission receiver /// @param result address Address of Opium commission receiver function getOpiumAddress() external view returns (address result) { return opiumAddress; } } // File: contracts/Errors/UsingRegistryErrors.sol pragma solidity 0.5.16; contract UsingRegistryErrors { string constant internal ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED = "USING_REGISTRY:ONLY_CORE_ALLOWED"; } // File: contracts/Lib/UsingRegistry.sol pragma solidity 0.5.16; /// @title Opium.Lib.UsingRegistry contract should be inherited by contracts, that are going to use Opium.Registry contract UsingRegistry is UsingRegistryErrors { // Emitted when registry instance is set event RegistrySet(address registry); // Instance of Opium.Registry contract Registry internal registry; /// @notice This modifier restricts access to functions, which could be called only by Opium.Core modifier onlyCore() { require(msg.sender == registry.getCore(), ERROR_USING_REGISTRY_ONLY_CORE_ALLOWED); _; } /// @notice Defines registry instance and emits appropriate event constructor(address _registry) public { registry = Registry(_registry); emit RegistrySet(_registry); } /// @notice Getter for registry variable /// @return address Address of registry set in current contract function getRegistry() external view returns (address) { return address(registry); } } // File: contracts/Lib/LibCommission.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibCommission contract defines constants for Opium commissions contract LibCommission { // Represents 100% base for commissions calculation uint256 constant public COMMISSION_BASE = 10000; // Represents 100% base for Opium commission uint256 constant public OPIUM_COMMISSION_BASE = 10; // Represents which part of `syntheticId` author commissions goes to opium uint256 constant public OPIUM_COMMISSION_PART = 1; } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // File: erc721o/contracts/Libs/UintArray.sol pragma solidity ^0.5.4; library UintArray { function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (0, false); } function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } function difference(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 count = 0; // First count the new length because can't push for in-memory arrays for (uint256 i = 0; i < length; i++) { uint256 e = A[i]; if (!contains(B, e)) { includeMap[i] = true; count++; } } uint256[] memory newUints = new uint256[](count); uint256[] memory newUintsIdxs = new uint256[](count); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsIdxs[j] = i; j++; } } return (newUints, newUintsIdxs); } function intersect(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory, uint256[] memory, uint256[] memory) { uint256 length = A.length; bool[] memory includeMap = new bool[](length); uint256 newLength = 0; for (uint256 i = 0; i < length; i++) { if (contains(B, A[i])) { includeMap[i] = true; newLength++; } } uint256[] memory newUints = new uint256[](newLength); uint256[] memory newUintsAIdxs = new uint256[](newLength); uint256[] memory newUintsBIdxs = new uint256[](newLength); uint256 j = 0; for (uint256 i = 0; i < length; i++) { if (includeMap[i]) { newUints[j] = A[i]; newUintsAIdxs[j] = i; (newUintsBIdxs[j], ) = indexOf(B, A[i]); j++; } } return (newUints, newUintsAIdxs, newUintsBIdxs); } function isUnique(uint256[] memory A) internal pure returns (bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { (uint256 idx, bool isIn) = indexOf(A, A[i]); if (isIn && idx < i) { return false; } } return true; } } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.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-solidity/contracts/introspection/ERC165.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: erc721o/contracts/Interfaces/IERC721O.sol pragma solidity ^0.5.4; contract IERC721O { // Token description function name() external view returns (string memory); function symbol() external view returns (string memory); function totalSupply() public view returns (uint256); function exists(uint256 _tokenId) public view returns (bool); function implementsERC721() public pure returns (bool); function tokenByIndex(uint256 _index) public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri); function getApproved(uint256 _tokenId) public view returns (address); function implementsERC721O() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address _owner); function balanceOf(address owner) public view returns (uint256); function balanceOf(address _owner, uint256 _tokenId) public view returns (uint256); function tokensOwned(address _owner) public view returns (uint256[] memory, uint256[] memory); // Non-Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public; // Non-Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId) public; // Fungible Unsafe Transfer function transfer(address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Unsafe Transfer From function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _quantity) public; // Fungible Safe Transfer From function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public; // Fungible Safe Batch Transfer From function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; function safeBatchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data) public; // Fungible Unsafe Batch Transfer From function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public; // Approvals function setApprovalForAll(address _operator, bool _approved) public; function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator); function isApprovedOrOwner(address _spender, address _owner, uint256 _tokenId) public view returns (bool); function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external; // Composable function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public; function recompose(uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity) public; // Required Events event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event TransferWithQuantity(address indexed from, address indexed to, uint256 indexed tokenId, uint256 quantity); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event BatchTransfer(address indexed from, address indexed to, uint256[] tokenTypes, uint256[] amounts); event Composition(uint256 portfolioId, uint256[] tokenIds, uint256[] tokenRatio); } // File: erc721o/contracts/Interfaces/IERC721OReceiver.sol pragma solidity ^0.5.4; /** * @title ERC721O token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721O contracts. */ contract IERC721OReceiver { /** * @dev Magic value to be returned upon successful reception of an amount of ERC721O tokens * ERC721O_RECEIVED = `bytes4(keccak256("onERC721OReceived(address,address,uint256,uint256,bytes)"))` = 0xf891ffe0 * ERC721O_BATCH_RECEIVED = `bytes4(keccak256("onERC721OBatchReceived(address,address,uint256[],uint256[],bytes)"))` = 0xd0e17c0b */ bytes4 constant internal ERC721O_RECEIVED = 0xf891ffe0; bytes4 constant internal ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function onERC721OReceived( address _operator, address _from, uint256 tokenId, uint256 amount, bytes memory data ) public returns(bytes4); function onERC721OBatchReceived( address _operator, address _from, uint256[] memory _types, uint256[] memory _amounts, bytes memory _data ) public returns (bytes4); } // File: erc721o/contracts/Libs/ObjectsLib.sol pragma solidity ^0.5.4; library ObjectLib { // Libraries using SafeMath for uint256; enum Operations { ADD, SUB, REPLACE } // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param _tokenId Object type * @return (Bin number, ID's index within that bin) */ function getTokenBinIndex(uint256 _tokenId) internal pure returns (uint256 bin, uint256 index) { bin = _tokenId * TYPES_BITS_SIZE / 256; index = _tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in _binBalances * @param _binBalances Uint256 containing the balances of objects * @param _index Index of the object in the provided bin * @param _amount Value to update the type balance * @param _operation Which operation to conduct : * Operations.REPLACE : Replace type balance with _amount * Operations.ADD : ADD _amount to type balance * Operations.SUB : Substract _amount from type balance */ function updateTokenBalance( uint256 _binBalances, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinBalance) { uint256 objectBalance; if (_operation == Operations.ADD) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.add(_amount)); } else if (_operation == Operations.SUB) { objectBalance = getValueInBin(_binBalances, _index); newBinBalance = writeValueInBin(_binBalances, _index, objectBalance.sub(_amount)); } else if (_operation == Operations.REPLACE) { newBinBalance = writeValueInBin(_binBalances, _index, _amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in _binValue at position _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index index at which to retrieve value * @return Value at given _index in _bin */ function getValueInBin(uint256 _binValue, uint256 _index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue >> rightShift) & mask; } /** * @dev return the updated _binValue after writing _amount at _index * @param _binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param _index Index at which to retrieve value * @param _amount Value to store at _index in _bin * @return Value at given _index in _bin */ function writeValueInBin(uint256 _binValue, uint256 _index, uint256 _amount) internal pure returns (uint256) { require(_amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (_index + 1); return (_binValue & ~(mask << leftShift) ) | (_amount << leftShift); } } // File: erc721o/contracts/ERC721OBase.sol pragma solidity ^0.5.4; contract ERC721OBase is IERC721O, ERC165, IERC721 { // Libraries using ObjectLib for ObjectLib.Operations; using ObjectLib for uint256; // Array with all tokenIds uint256[] internal allTokens; // Packed balances mapping(address => mapping(uint256 => uint256)) internal packedTokenBalance; // Operators mapping(address => mapping(address => bool)) internal operators; // Keeps aprovals for tokens from owner to approved address // tokenApprovals[tokenId][owner] = approved mapping (uint256 => mapping (address => address)) internal tokenApprovals; // Token Id state mapping(uint256 => uint256) internal tokenTypes; uint256 constant internal INVALID = 0; uint256 constant internal POSITION = 1; uint256 constant internal PORTFOLIO = 2; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721O = 0x12345678; // EIP712 constants bytes32 public DOMAIN_SEPARATOR; bytes32 public PERMIT_TYPEHASH; // mapping holds nonces for approval permissions // nonces[holder] => nonce mapping (address => uint) public nonces; modifier isOperatorOrOwner(address _from) { require((msg.sender == _from) || operators[_from][msg.sender], "msg.sender is neither _from nor operator"); _; } constructor() public { _registerInterface(INTERFACE_ID_ERC721O); // Calculate EIP712 constants DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,address verifyingContract)"), keccak256(bytes("ERC721o")), keccak256(bytes("1")), address(this) )); PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); } function implementsERC721O() public pure returns (bool) { return true; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { return tokenTypes[_tokenId] != INVALID; } /** * @dev return the _tokenId type' balance of _address * @param _address Address to query balance of * @param _tokenId type to query balance of * @return Amount of objects of a given type ID */ function balanceOf(address _address, uint256 _tokenId) public view returns (uint256) { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); return packedTokenBalance[_address][bin].getValueInBin(index); } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets Iterate through the list of existing tokens and return the indexes * and balances of the tokens owner by the user * @param _owner The adddress we are checking * @return indexes The tokenIds * @return balances The balances of each token */ function tokensOwned(address _owner) public view returns (uint256[] memory indexes, uint256[] memory balances) { uint256 numTokens = totalSupply(); uint256[] memory tokenIndexes = new uint256[](numTokens); uint256[] memory tempTokens = new uint256[](numTokens); uint256 count; for (uint256 i = 0; i < numTokens; i++) { uint256 tokenId = allTokens[i]; if (balanceOf(_owner, tokenId) > 0) { tempTokens[count] = balanceOf(_owner, tokenId); tokenIndexes[count] = tokenId; count++; } } // copy over the data to a correct size array uint256[] memory _ownedTokens = new uint256[](count); uint256[] memory _ownedTokensIndexes = new uint256[](count); for (uint256 i = 0; i < count; i++) { _ownedTokens[i] = tempTokens[i]; _ownedTokensIndexes[i] = tokenIndexes[i]; } return (_ownedTokensIndexes, _ownedTokens); } /** * @dev Will set _operator operator status to true or false * @param _operator Address to changes operator status. * @param _approved _operator's new operator status (true or false) */ function setApprovalForAll(address _operator, bool _approved) public { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /// @notice Approve for all by signature function permit(address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, bytes calldata _signature) external { // Calculate hash bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode( PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed )) )); // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly bytes32 r; bytes32 s; uint8 v; bytes memory signature = _signature; assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) v := byte(0, mload(add(signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } address recoveredAddress; // If the version is correct return the signer address if (v != 27 && v != 28) { recoveredAddress = address(0); } else { // solium-disable-next-line arg-overflow recoveredAddress = ecrecover(digest, v, r, s); } require(_holder != address(0), "Holder can't be zero address"); require(_holder == recoveredAddress, "Signer address is invalid"); require(_expiry == 0 || now <= _expiry, "Permission expired"); require(_nonce == nonces[_holder]++, "Nonce is invalid"); // Update operator status operators[_holder][_spender] = _allowed; emit ApprovalForAll(_holder, _spender, _allowed); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { require(_to != msg.sender, "Can't approve to yourself"); tokenApprovals[_tokenId][msg.sender] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId, address _tokenOwner) public view returns (address) { return tokenApprovals[_tokenId][_tokenOwner]; } /** * @dev Function that verifies whether _operator is an authorized operator of _tokenHolder. * @param _operator The address of the operator to query status of * @param _owner Address of the tokenHolder * @return A uint256 specifying the amount of tokens still available for the spender. */ function isApprovedForAll(address _owner, address _operator) public view returns (bool isOperator) { return operators[_owner][_operator]; } function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) ); } function _updateTokenBalance( address _from, uint256 _tokenId, uint256 _amount, ObjectLib.Operations op ) internal { (uint256 bin, uint256 index) = _tokenId.getTokenBinIndex(); packedTokenBalance[_from][bin] = packedTokenBalance[_from][bin].updateTokenBalance( index, _amount, op ); } } // File: erc721o/contracts/ERC721OTransferable.sol pragma solidity ^0.5.4; contract ERC721OTransferable is ERC721OBase, ReentrancyGuard { // Libraries using Address for address; // safeTransfer constants bytes4 internal constant ERC721O_RECEIVED = 0xf891ffe0; bytes4 internal constant ERC721O_BATCH_RECEIVED = 0xd0e17c0b; function batchTransferFrom(address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts) public { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * @param _data Data to pass to onERC721OReceived() function if recipient is contract * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts, bytes memory _data ) public nonReentrant { // Batch Transfering _batchTransferFrom(_from, _to, _tokenIds, _amounts); // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC721OReceiver(_to).onERC721OBatchReceived( msg.sender, _from, _tokenIds, _amounts, _data ); require(retval == ERC721O_BATCH_RECEIVED); } } function safeBatchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) public { safeBatchTransferFrom(_from, _to, _tokenIds, _amounts, ""); } function transfer(address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(msg.sender, _to, _tokenId, _amount); } function transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { _transferFrom(_from, _to, _tokenId, _amount); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) public { safeTransferFrom(_from, _to, _tokenId, _amount, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, _amount); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _amount, _data), "Sent to a contract which is not an ERC721O receiver" ); } /** * @dev transfer objects from different tokenIds to specified address * @param _from The address to BatchTransfer objects from. * @param _to The address to batchTransfer objects to. * @param _tokenIds Array of tokenIds to update balance of * @param _amounts Array of amount of object per type to be transferred. * Note: Arrays should be sorted so that all tokenIds in a same bin are adjacent (more efficient). */ function _batchTransferFrom( address _from, address _to, uint256[] memory _tokenIds, uint256[] memory _amounts ) internal isOperatorOrOwner(_from) { // Requirements require(_tokenIds.length == _amounts.length, "Inconsistent array length between args"); require(_to != address(0), "Invalid to address"); // Number of transfers to execute uint256 nTransfer = _tokenIds.length; // Don't do useless calculations if (_from == _to) { for (uint256 i = 0; i < nTransfer; i++) { emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } return; } for (uint256 i = 0; i < nTransfer; i++) { require(_amounts[i] <= balanceOf(_from, _tokenIds[i]), "Quantity greater than from balance"); _updateTokenBalance(_from, _tokenIds[i], _amounts[i], ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenIds[i], _amounts[i], ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenIds[i]); emit TransferWithQuantity(_from, _to, _tokenIds[i], _amounts[i]); } // Emit batchTransfer event emit BatchTransfer(_from, _to, _tokenIds, _amounts); } function _transferFrom(address _from, address _to, uint256 _tokenId, uint256 _amount) internal { require(isApprovedOrOwner(msg.sender, _from, _tokenId), "Not approved"); require(_amount <= balanceOf(_from, _tokenId), "Quantity greater than from balance"); require(_to != address(0), "Invalid to address"); _updateTokenBalance(_from, _tokenId, _amount, ObjectLib.Operations.SUB); _updateTokenBalance(_to, _tokenId, _amount, ObjectLib.Operations.ADD); emit Transfer(_from, _to, _tokenId); emit TransferWithQuantity(_from, _to, _tokenId, _amount); } function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, uint256 _amount, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721OReceiver(_to).onERC721OReceived(msg.sender, _from, _tokenId, _amount, _data); return(retval == ERC721O_RECEIVED); } } // File: erc721o/contracts/ERC721OMintable.sol pragma solidity ^0.5.4; contract ERC721OMintable is ERC721OTransferable { // Libraries using LibPosition for bytes32; // Internal functions function _mint(uint256 _tokenId, address _to, uint256 _supply) internal { // If the token doesn't exist, add it to the tokens array if (!exists(_tokenId)) { tokenTypes[_tokenId] = POSITION; allTokens.push(_tokenId); } _updateTokenBalance(_to, _tokenId, _supply, ObjectLib.Operations.ADD); emit Transfer(address(0), _to, _tokenId); emit TransferWithQuantity(address(0), _to, _tokenId, _supply); } function _burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) internal { uint256 ownerBalance = balanceOf(_tokenOwner, _tokenId); require(ownerBalance >= _quantity, "TOKEN_MINTER:NOT_ENOUGH_POSITIONS"); _updateTokenBalance(_tokenOwner, _tokenId, _quantity, ObjectLib.Operations.SUB); emit Transfer(_tokenOwner, address(0), _tokenId); emit TransferWithQuantity(_tokenOwner, address(0), _tokenId, _quantity); } function _mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { _mintLong(_buyer, _derivativeHash, _quantity); _mintShort(_seller, _derivativeHash, _quantity); } function _mintLong(address _buyer, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 longTokenId = _derivativeHash.getLongTokenId(); _mint(longTokenId, _buyer, _quantity); } function _mintShort(address _seller, bytes32 _derivativeHash, uint256 _quantity) internal { uint256 shortTokenId = _derivativeHash.getShortTokenId(); _mint(shortTokenId, _seller, _quantity); } function _registerPortfolio(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio) internal { if (!exists(_portfolioId)) { tokenTypes[_portfolioId] = PORTFOLIO; emit Composition(_portfolioId, _tokenIds, _tokenRatio); } } } // File: erc721o/contracts/ERC721OComposable.sol pragma solidity ^0.5.4; contract ERC721OComposable is ERC721OMintable { // Libraries using UintArray for uint256[]; using SafeMath for uint256; function compose(uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); for (uint256 i = 0; i < _tokenIds.length; i++) { _burn(msg.sender, _tokenIds[i], _tokenRatio[i].mul(_quantity)); } uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); _registerPortfolio(portfolioId, _tokenIds, _tokenRatio); _mint(portfolioId, msg.sender, _quantity); } function decompose(uint256 _portfolioId, uint256[] memory _tokenIds, uint256[] memory _tokenRatio, uint256 _quantity) public { require(_tokenIds.length == _tokenRatio.length, "TOKEN_MINTER:TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_tokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 portfolioId = uint256(keccak256(abi.encodePacked( _tokenIds, _tokenRatio ))); require(portfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); for (uint256 i = 0; i < _tokenIds.length; i++) { _mint(_tokenIds[i], msg.sender, _tokenRatio[i].mul(_quantity)); } } function recompose( uint256 _portfolioId, uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) public { require(_initialTokenIds.length == _initialTokenRatio.length, "TOKEN_MINTER:INITIAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_finalTokenIds.length == _finalTokenRatio.length, "TOKEN_MINTER:FINAL_TOKEN_IDS_AND_RATIO_LENGTH_DOES_NOT_MATCH"); require(_quantity > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_finalTokenIds.length > 0, "TOKEN_MINTER:WRONG_QUANTITY"); require(_initialTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); require(_finalTokenIds.isUnique(), "TOKEN_MINTER:TOKEN_IDS_NOT_UNIQUE"); uint256 oldPortfolioId = uint256(keccak256(abi.encodePacked( _initialTokenIds, _initialTokenRatio ))); require(oldPortfolioId == _portfolioId, "TOKEN_MINTER:WRONG_PORTFOLIO_ID"); _burn(msg.sender, _portfolioId, _quantity); _removedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _addedIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); _keptIds(_initialTokenIds, _initialTokenRatio, _finalTokenIds, _finalTokenRatio, _quantity); uint256 newPortfolioId = uint256(keccak256(abi.encodePacked( _finalTokenIds, _finalTokenRatio ))); _registerPortfolio(newPortfolioId, _finalTokenIds, _finalTokenRatio); _mint(newPortfolioId, msg.sender, _quantity); } function _removedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory removedIds, uint256[] memory removedIdsIdxs) = _initialTokenIds.difference(_finalTokenIds); for (uint256 i = 0; i < removedIds.length; i++) { uint256 index = removedIdsIdxs[i]; _mint(_initialTokenIds[index], msg.sender, _initialTokenRatio[index].mul(_quantity)); } _finalTokenRatio; } function _addedIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory addedIds, uint256[] memory addedIdsIdxs) = _finalTokenIds.difference(_initialTokenIds); for (uint256 i = 0; i < addedIds.length; i++) { uint256 index = addedIdsIdxs[i]; _burn(msg.sender, _finalTokenIds[index], _finalTokenRatio[index].mul(_quantity)); } _initialTokenRatio; } function _keptIds( uint256[] memory _initialTokenIds, uint256[] memory _initialTokenRatio, uint256[] memory _finalTokenIds, uint256[] memory _finalTokenRatio, uint256 _quantity ) private { (uint256[] memory keptIds, uint256[] memory keptInitialIdxs, uint256[] memory keptFinalIdxs) = _initialTokenIds.intersect(_finalTokenIds); for (uint256 i = 0; i < keptIds.length; i++) { uint256 initialIndex = keptInitialIdxs[i]; uint256 finalIndex = keptFinalIdxs[i]; if (_initialTokenRatio[initialIndex] > _finalTokenRatio[finalIndex]) { uint256 diff = _initialTokenRatio[initialIndex] - _finalTokenRatio[finalIndex]; _mint(_initialTokenIds[initialIndex], msg.sender, diff.mul(_quantity)); } else if (_initialTokenRatio[initialIndex] < _finalTokenRatio[finalIndex]) { uint256 diff = _finalTokenRatio[finalIndex] - _initialTokenRatio[initialIndex]; _burn(msg.sender, _initialTokenIds[initialIndex], diff.mul(_quantity)); } } } } // File: erc721o/contracts/Libs/UintsLib.sol pragma solidity ^0.5.4; library UintsLib { function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } // File: erc721o/contracts/ERC721OBackwardCompatible.sol pragma solidity ^0.5.4; contract ERC721OBackwardCompatible is ERC721OComposable { using UintsLib for uint256; // Interface constants bytes4 internal constant INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 internal constant INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 internal constant INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Reciever constants bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; // Metadata URI string internal baseTokenURI; constructor(string memory _baseTokenURI) public ERC721OBase() { baseTokenURI = _baseTokenURI; _registerInterface(INTERFACE_ID_ERC721); _registerInterface(INTERFACE_ID_ERC721_ENUMERABLE); _registerInterface(INTERFACE_ID_ERC721_METADATA); } // ERC721 compatibility function implementsERC721() public pure returns (bool) { return true; } /** * @dev Gets the owner of a given NFT * @param _tokenId uint256 representing the unique token identifier * @return address the owner of the token */ function ownerOf(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } /** * @dev Gets the number of tokens owned by the address we are checking * @param _owner The adddress we are checking * @return balance The unique amount of tokens owned */ function balanceOf(address _owner) public view returns (uint256 balance) { (, uint256[] memory tokens) = tokensOwned(_owner); return tokens.length; } // ERC721 - Enumerable compatibility /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId) { (, uint256[] memory tokens) = tokensOwned(_owner); require(_index < tokens.length); return tokens[_index]; } // ERC721 - Metadata compatibility function tokenURI(uint256 _tokenId) public view returns (string memory tokenUri) { require(exists(_tokenId), "Token doesn't exist"); return string(abi.encodePacked( baseTokenURI, _tokenId.uint2str(), ".json" )); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { if (exists(_tokenId)) { return address(this); } return address(0); } function safeTransferFrom(address _from, address _to, uint256 _tokenId) public { safeTransferFrom(_from, _to, _tokenId, ""); } function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public nonReentrant { _transferFrom(_from, _to, _tokenId, 1); require( _checkAndCallSafeTransfer(_from, _to, _tokenId, _data), "Sent to a contract which is not an ERC721 receiver" ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { _transferFrom(_from, _to, _tokenId, 1); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function _checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes memory _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = IERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data ); return (retval == ERC721_RECEIVED); } } // File: contracts/TokenMinter.sol pragma solidity 0.5.16; /// @title Opium.TokenMinter contract implements ERC721O token standard for minting, burning and transferring position tokens contract TokenMinter is ERC721OBackwardCompatible, UsingRegistry { /// @notice Calls constructors of super-contracts /// @param _baseTokenURI string URI for token explorers /// @param _registry address Address of Opium.registry constructor(string memory _baseTokenURI, address _registry) public ERC721OBackwardCompatible(_baseTokenURI) UsingRegistry(_registry) {} /// @notice Mints LONG and SHORT position tokens /// @param _buyer address Address of LONG position receiver /// @param _seller address Address of SHORT position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, address _seller, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mint(_buyer, _seller, _derivativeHash, _quantity); } /// @notice Mints only LONG position tokens for "pooled" derivatives /// @param _buyer address Address of LONG position receiver /// @param _derivativeHash bytes32 Hash of derivative (ticker) of position /// @param _quantity uint256 Quantity of positions to mint function mint(address _buyer, bytes32 _derivativeHash, uint256 _quantity) external onlyCore { _mintLong(_buyer, _derivativeHash, _quantity); } /// @notice Burns position tokens /// @param _tokenOwner address Address of tokens owner /// @param _tokenId uint256 tokenId of positions to burn /// @param _quantity uint256 Quantity of positions to burn function burn(address _tokenOwner, uint256 _tokenId, uint256 _quantity) external onlyCore { _burn(_tokenOwner, _tokenId, _quantity); } /// @notice ERC721 interface compatible function for position token name retrieving /// @return Returns name of token function name() external view returns (string memory) { return "Opium Network Position Token"; } /// @notice ERC721 interface compatible function for position token symbol retrieving /// @return Returns symbol of token function symbol() external view returns (string memory) { return "ONP"; } /// VIEW FUNCTIONS /// @notice Checks whether _spender is approved to spend tokens on _owners behalf or owner itself /// @param _spender address Address of spender /// @param _owner address Address of owner /// @param _tokenId address tokenId of interest /// @return Returns whether _spender is approved to spend tokens function isApprovedOrOwner( address _spender, address _owner, uint256 _tokenId ) public view returns (bool) { return ( _spender == _owner || getApproved(_tokenId, _owner) == _spender || isApprovedForAll(_owner, _spender) || isOpiumSpender(_spender) ); } /// @notice Checks whether _spender is Opium.TokenSpender /// @return Returns whether _spender is Opium.TokenSpender function isOpiumSpender(address _spender) public view returns (bool) { return _spender == registry.getTokenSpender(); } } // File: contracts/Errors/OracleAggregatorErrors.sol pragma solidity 0.5.16; contract OracleAggregatorErrors { string constant internal ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER = "ORACLE_AGGREGATOR:NOT_ENOUGH_ETHER"; string constant internal ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE = "ORACLE_AGGREGATOR:QUERY_WAS_ALREADY_MADE"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST = "ORACLE_AGGREGATOR:DATA_DOESNT_EXIST"; string constant internal ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST = "ORACLE_AGGREGATOR:DATA_ALREADY_EXIST"; } // File: contracts/Interface/IOracleId.sol pragma solidity 0.5.16; /// @title Opium.Interface.IOracleId contract is an interface that every oracleId should implement interface IOracleId { /// @notice Requests data from `oracleId` one time /// @param timestamp uint256 Timestamp at which data are needed function fetchData(uint256 timestamp) external payable; /// @notice Requests data from `oracleId` multiple times /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(uint256 timestamp, uint256 period, uint256 times) external payable; /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice() external returns (uint256 fetchPrice); // Event with oracleId metadata JSON string (for DIB.ONE derivative explorer) event MetadataSet(string metadata); } // File: contracts/OracleAggregator.sol pragma solidity 0.5.16; /// @title Opium.OracleAggregator contract requests and caches the data from `oracleId`s and provides them to the Core for positions execution contract OracleAggregator is OracleAggregatorErrors, ReentrancyGuard { using SafeMath for uint256; // Storage for the `oracleId` results // dataCache[oracleId][timestamp] => data mapping (address => mapping(uint256 => uint256)) public dataCache; // Flags whether data were provided // dataExist[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataExist; // Flags whether data were requested // dataRequested[oracleId][timestamp] => bool mapping (address => mapping(uint256 => bool)) public dataRequested; // MODIFIERS /// @notice Checks whether enough ETH were provided withing data request to proceed /// @param oracleId address Address of the `oracleId` smart contract /// @param times uint256 How many times the `oracleId` is being requested modifier enoughEtherProvided(address oracleId, uint256 times) { // Calling Opium.IOracleId function to get the data fetch price per one request uint256 oneTimePrice = calculateFetchPrice(oracleId); // Checking if enough ether was provided for `times` amount of requests require(msg.value >= oneTimePrice.mul(times), ERROR_ORACLE_AGGREGATOR_NOT_ENOUGH_ETHER); _; } // PUBLIC FUNCTIONS /// @notice Requests data from `oracleId` one time /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed function fetchData(address oracleId, uint256 timestamp) public payable nonReentrant enoughEtherProvided(oracleId, 1) { // Check if was not requested before and mark as requested _registerQuery(oracleId, timestamp); // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).fetchData.value(msg.value)(timestamp); } /// @notice Requests data from `oracleId` multiple times /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are needed for the first time /// @param period uint256 Period in seconds between multiple timestamps /// @param times uint256 How many timestamps are requested function recursivelyFetchData(address oracleId, uint256 timestamp, uint256 period, uint256 times) public payable nonReentrant enoughEtherProvided(oracleId, times) { // Check if was not requested before and mark as requested in loop for each timestamp for (uint256 i = 0; i < times; i++) { _registerQuery(oracleId, timestamp + period * i); } // Call the `oracleId` contract and transfer ETH IOracleId(oracleId).recursivelyFetchData.value(msg.value)(timestamp, period, times); } /// @notice Receives and caches data from `msg.sender` /// @param timestamp uint256 Timestamp of data /// @param data uint256 Data itself function __callback(uint256 timestamp, uint256 data) public { // Don't allow to push data twice require(!dataExist[msg.sender][timestamp], ERROR_ORACLE_AGGREGATOR_DATA_ALREADY_EXIST); // Saving data dataCache[msg.sender][timestamp] = data; // Flagging that data were received dataExist[msg.sender][timestamp] = true; } /// @notice Requests and returns price in ETH for one request. This function could be called as `view` function. Oraclize API for price calculations restricts making this function as view. /// @param oracleId address Address of the `oracleId` smart contract /// @return fetchPrice uint256 Price of one data request in ETH function calculateFetchPrice(address oracleId) public returns(uint256 fetchPrice) { fetchPrice = IOracleId(oracleId).calculateFetchPrice(); } // PRIVATE FUNCTIONS /// @notice Checks if data was not requested and provided before and marks as requested /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data are requested function _registerQuery(address oracleId, uint256 timestamp) private { // Check if data was not requested and provided yet require(!dataRequested[oracleId][timestamp] && !dataExist[oracleId][timestamp], ERROR_ORACLE_AGGREGATOR_QUERY_WAS_ALREADY_MADE); // Mark as requested dataRequested[oracleId][timestamp] = true; } // VIEW FUNCTIONS /// @notice Returns cached data if they exist, or reverts with an error /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @return dataResult uint256 Cached data provided by `oracleId` function getData(address oracleId, uint256 timestamp) public view returns(uint256 dataResult) { // Check if Opium.OracleAggregator has data require(hasData(oracleId, timestamp), ERROR_ORACLE_AGGREGATOR_DATA_DOESNT_EXIST); // Return cached data dataResult = dataCache[oracleId][timestamp]; } /// @notice Getter for dataExist mapping /// @param oracleId address Address of the `oracleId` smart contract /// @param timestamp uint256 Timestamp at which data were requested /// @param result bool Returns whether data were provided already function hasData(address oracleId, uint256 timestamp) public view returns(bool result) { return dataExist[oracleId][timestamp]; } } // File: contracts/Errors/SyntheticAggregatorErrors.sol pragma solidity 0.5.16; contract SyntheticAggregatorErrors { string constant internal ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH = "SYNTHETIC_AGGREGATOR:DERIVATIVE_HASH_NOT_MATCH"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN = "SYNTHETIC_AGGREGATOR:WRONG_MARGIN"; string constant internal ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG = "SYNTHETIC_AGGREGATOR:COMMISSION_TOO_BIG"; } // File: contracts/SyntheticAggregator.sol pragma solidity 0.5.16; /// @notice Opium.SyntheticAggregator contract initialized, identifies and caches syntheticId sensitive data contract SyntheticAggregator is SyntheticAggregatorErrors, LibDerivative, LibCommission, ReentrancyGuard { // Emitted when new ticker is initialized event Create(Derivative derivative, bytes32 derivativeHash); // Enum for types of syntheticId // Invalid - syntheticId is not initialized yet // NotPool - syntheticId with p2p logic // Pool - syntheticId with pooled logic enum SyntheticTypes { Invalid, NotPool, Pool } // Cache of buyer margin by ticker // buyerMarginByHash[derivativeHash] = buyerMargin mapping (bytes32 => uint256) public buyerMarginByHash; // Cache of seller margin by ticker // sellerMarginByHash[derivativeHash] = sellerMargin mapping (bytes32 => uint256) public sellerMarginByHash; // Cache of type by ticker // typeByHash[derivativeHash] = type mapping (bytes32 => SyntheticTypes) public typeByHash; // Cache of commission by ticker // commissionByHash[derivativeHash] = commission mapping (bytes32 => uint256) public commissionByHash; // Cache of author addresses by ticker // authorAddressByHash[derivativeHash] = authorAddress mapping (bytes32 => address) public authorAddressByHash; // PUBLIC FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return commission uint256 Synthetic author commission function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns `syntheticId` author address from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return authorAddress address Synthetic author address function getAuthorAddress(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (address authorAddress) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); authorAddress = authorAddressByHash[_derivativeHash]; } /// @notice Initializes ticker, if was not initialized and returns buyer and seller margin from cache /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return buyerMargin uint256 Margin of buyer /// @return sellerMargin uint256 Margin of seller function getMargin(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 buyerMargin, uint256 sellerMargin) { // If it's a pool, just return margin from syntheticId contract if (_isPool(_derivativeHash, _derivative)) { return IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); } // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); // Check if margins for _derivativeHash were already cached buyerMargin = buyerMarginByHash[_derivativeHash]; sellerMargin = sellerMarginByHash[_derivativeHash]; } /// @notice Checks whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function isPool(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (bool result) { result = _isPool(_derivativeHash, _derivative); } // PRIVATE FUNCTIONS /// @notice Initializes ticker, if was not initialized and returns whether `syntheticId` implements pooled logic /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself /// @return result bool Returns whether synthetic implements pooled logic function _isPool(bytes32 _derivativeHash, Derivative memory _derivative) private returns (bool result) { // Initialize derivative if wasn't initialized before _initDerivative(_derivativeHash, _derivative); result = typeByHash[_derivativeHash] == SyntheticTypes.Pool; } /// @notice Initializes ticker: caches syntheticId type, margin, author address and commission /// @param _derivativeHash bytes32 Hash of derivative /// @param _derivative Derivative Derivative itself function _initDerivative(bytes32 _derivativeHash, Derivative memory _derivative) private { // Check if type for _derivativeHash was already cached SyntheticTypes syntheticType = typeByHash[_derivativeHash]; // Type could not be Invalid, thus this condition says us that type was not cached before if (syntheticType != SyntheticTypes.Invalid) { return; } // For security reasons we calculate hash of provided _derivative bytes32 derivativeHash = getDerivativeHash(_derivative); require(derivativeHash == _derivativeHash, ERROR_SYNTHETIC_AGGREGATOR_DERIVATIVE_HASH_NOT_MATCH); // POOL // Get isPool from SyntheticId bool result = IDerivativeLogic(_derivative.syntheticId).isPool(); // Cache type returned from synthetic typeByHash[derivativeHash] = result ? SyntheticTypes.Pool : SyntheticTypes.NotPool; // MARGIN // Get margin from SyntheticId (uint256 buyerMargin, uint256 sellerMargin) = IDerivativeLogic(_derivative.syntheticId).getMargin(_derivative); // We are not allowing both margins to be equal to 0 require(buyerMargin != 0 || sellerMargin != 0, ERROR_SYNTHETIC_AGGREGATOR_WRONG_MARGIN); // Cache margins returned from synthetic buyerMarginByHash[derivativeHash] = buyerMargin; sellerMarginByHash[derivativeHash] = sellerMargin; // AUTHOR ADDRESS // Cache author address returned from synthetic authorAddressByHash[derivativeHash] = IDerivativeLogic(_derivative.syntheticId).getAuthorAddress(); // AUTHOR COMMISSION // Get commission from syntheticId uint256 commission = IDerivativeLogic(_derivative.syntheticId).getAuthorCommission(); // Check if commission is not set > 100% require(commission <= COMMISSION_BASE, ERROR_SYNTHETIC_AGGREGATOR_COMMISSION_TOO_BIG); // Cache commission commissionByHash[derivativeHash] = commission; // If we are here, this basically means this ticker was not used before, so we emit an event for Dapps developers about new ticker (derivative) and it's hash emit Create(_derivative, derivativeHash); } } // File: contracts/Lib/Whitelisted.sol pragma solidity 0.5.16; /// @title Opium.Lib.Whitelisted contract implements whitelist with modifier to restrict access to only whitelisted addresses contract Whitelisted { // Whitelist array address[] internal whitelist; /// @notice This modifier restricts access to functions, which could be called only by whitelisted addresses modifier onlyWhitelisted() { // Allowance flag bool allowed = false; // Going through whitelisted addresses array uint256 whitelistLength = whitelist.length; for (uint256 i = 0; i < whitelistLength; i++) { // If `msg.sender` is met within whitelisted addresses, raise the flag and exit the loop if (whitelist[i] == msg.sender) { allowed = true; break; } } // Check if flag was raised require(allowed, "Only whitelisted allowed"); _; } /// @notice Getter for whitelisted addresses array /// @return Array of whitelisted addresses function getWhitelist() public view returns (address[] memory) { return whitelist; } } // File: contracts/Lib/WhitelistedWithGovernance.sol pragma solidity 0.5.16; /// @title Opium.Lib.WhitelistedWithGovernance contract implements Opium.Lib.Whitelisted and adds governance for whitelist controlling contract WhitelistedWithGovernance is Whitelisted { // Emitted when new governor is set event GovernorSet(address governor); // Emitted when new whitelist is proposed event Proposed(address[] whitelist); // Emitted when proposed whitelist is committed (set) event Committed(address[] whitelist); // Proposal life timelock interval uint256 public timeLockInterval; // Governor address address public governor; // Timestamp of last proposal uint256 public proposalTime; // Proposed whitelist address[] public proposedWhitelist; /// @notice This modifier restricts access to functions, which could be called only by governor modifier onlyGovernor() { require(msg.sender == governor, "Only governor allowed"); _; } /// @notice Contract constructor /// @param _timeLockInterval uint256 Initial value for timelock interval /// @param _governor address Initial value for governor constructor(uint256 _timeLockInterval, address _governor) public { timeLockInterval = _timeLockInterval; governor = _governor; emit GovernorSet(governor); } /// @notice Calling this function governor could propose new whitelist addresses array. Also it allows to initialize first whitelist if it was not initialized yet. function proposeWhitelist(address[] memory _whitelist) public onlyGovernor { // Restrict empty proposals require(_whitelist.length != 0, "Can't be empty"); // Consider empty whitelist as not initialized, as proposing of empty whitelists is not allowed // If whitelist has never been initialized, we set whitelist right away without proposal if (whitelist.length == 0) { whitelist = _whitelist; emit Committed(_whitelist); // Otherwise save current time as timestamp of proposal, save proposed whitelist and emit event } else { proposalTime = now; proposedWhitelist = _whitelist; emit Proposed(_whitelist); } } /// @notice Calling this function governor commits proposed whitelist if timelock interval of proposal was passed function commitWhitelist() public onlyGovernor { // Check if proposal was made require(proposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((proposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new whitelist and emit event whitelist = proposedWhitelist; emit Committed(whitelist); // Reset proposal time lock proposalTime = 0; } /// @notice This function allows governor to transfer governance to a new governor and emits event /// @param _governor address Address of new governor function setGovernor(address _governor) public onlyGovernor { require(_governor != address(0), "Can't set zero address"); governor = _governor; emit GovernorSet(governor); } } // File: contracts/Lib/WhitelistedWithGovernanceAndChangableTimelock.sol pragma solidity 0.5.16; /// @notice Opium.Lib.WhitelistedWithGovernanceAndChangableTimelock contract implements Opium.Lib.WhitelistedWithGovernance and adds possibility for governor to change timelock interval within timelock interval contract WhitelistedWithGovernanceAndChangableTimelock is WhitelistedWithGovernance { // Emitted when new timelock is proposed event Proposed(uint256 timelock); // Emitted when new timelock is committed (set) event Committed(uint256 timelock); // Timestamp of last timelock proposal uint256 public timeLockProposalTime; // Proposed timelock uint256 public proposedTimeLock; /// @notice Calling this function governor could propose new timelock /// @param _timelock uint256 New timelock value function proposeTimelock(uint256 _timelock) public onlyGovernor { timeLockProposalTime = now; proposedTimeLock = _timelock; emit Proposed(_timelock); } /// @notice Calling this function governor could commit previously proposed new timelock if timelock interval of proposal was passed function commitTimelock() public onlyGovernor { // Check if proposal was made require(timeLockProposalTime != 0, "Didn't proposed yet"); // Check if timelock interval was passed require((timeLockProposalTime + timeLockInterval) < now, "Can't commit yet"); // Set new timelock and emit event timeLockInterval = proposedTimeLock; emit Committed(proposedTimeLock); // Reset timelock time lock timeLockProposalTime = 0; } } // File: contracts/TokenSpender.sol pragma solidity 0.5.16; /// @title Opium.TokenSpender contract holds users ERC20 approvals and allows whitelisted contracts to use tokens contract TokenSpender is WhitelistedWithGovernanceAndChangableTimelock { using SafeERC20 for IERC20; // Initial timelock period uint256 public constant WHITELIST_TIMELOCK = 1 hours; /// @notice Calls constructors of super-contracts /// @param _governor address Address of governor, who is allowed to adjust whitelist constructor(address _governor) public WhitelistedWithGovernance(WHITELIST_TIMELOCK, _governor) {} /// @notice Using this function whitelisted contracts could call ERC20 transfers /// @param token IERC20 Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param amount uint256 Amount of tokens to be transferred function claimTokens(IERC20 token, address from, address to, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, amount); } /// @notice Using this function whitelisted contracts could call ERC721O transfers /// @param token IERC721O Instance of token /// @param from address Address from which tokens are transferred /// @param to address Address of tokens receiver /// @param tokenId uint256 Token ID to be transferred /// @param amount uint256 Amount of tokens to be transferred function claimPositions(IERC721O token, address from, address to, uint256 tokenId, uint256 amount) external onlyWhitelisted { token.safeTransferFrom(from, to, tokenId, amount); } } // File: contracts/Core.sol pragma solidity 0.5.16; /// @title Opium.Core contract creates positions, holds and distributes margin at the maturity contract Core is LibDerivative, LibCommission, UsingRegistry, CoreErrors, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emitted when Core creates new position event Created(address buyer, address seller, bytes32 derivativeHash, uint256 quantity); // Emitted when Core executes positions event Executed(address tokenOwner, uint256 tokenId, uint256 quantity); // Emitted when Core cancels ticker for the first time event Canceled(bytes32 derivativeHash); // Period of time after which ticker could be canceled if no data was provided to the `oracleId` uint256 public constant NO_DATA_CANCELLATION_PERIOD = 2 weeks; // Vaults for pools // This mapping holds balances of pooled positions // poolVaults[syntheticAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public poolVaults; // Vaults for fees // This mapping holds balances of fee recipients // feesVaults[feeRecipientAddress][tokenAddress] => availableBalance mapping (address => mapping(address => uint256)) public feesVaults; // Hashes of cancelled tickers mapping (bytes32 => bool) public cancelled; /// @notice Calls Core.Lib.UsingRegistry constructor constructor(address _registry) public UsingRegistry(_registry) {} // PUBLIC FUNCTIONS /// @notice This function allows fee recipients to withdraw their fees /// @param _tokenAddress address Address of an ERC20 token to withdraw function withdrawFee(address _tokenAddress) public nonReentrant { uint256 balance = feesVaults[msg.sender][_tokenAddress]; feesVaults[msg.sender][_tokenAddress] = 0; IERC20(_tokenAddress).safeTransfer(msg.sender, balance); } /// @notice Creates derivative contracts (positions) /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of derivatives to be created /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address - if seller is set to `address(0)`, consider as pooled position function create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) public nonReentrant { if (_addresses[1] == address(0)) { _createPooled(_derivative, _quantity, _addresses[0]); } else { _create(_derivative, _quantity, _addresses); } } /// @notice Executes several positions of `msg.sender` with same `tokenId` /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(msg.sender, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `_tokenOwner` with same `tokenId` /// @param _tokenOwner address Address of the owner of positions /// @param _tokenId uint256 `tokenId` of positions that needs to be executed /// @param _quantity uint256 Quantity of positions to execute /// @param _derivative Derivative Derivative definition function execute(address _tokenOwner, uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _execute(_tokenOwner, tokenIds, quantities, derivatives); } /// @notice Executes several positions of `msg.sender` with different `tokenId`s /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(msg.sender, _tokenIds, _quantities, _derivatives); } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _execute(_tokenOwner, _tokenIds, _quantities, _derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenId uint256 `tokenId` of positions that needs to be canceled /// @param _quantity uint256 Quantity of positions to cancel /// @param _derivative Derivative Derivative definition function cancel(uint256 _tokenId, uint256 _quantity, Derivative memory _derivative) public nonReentrant { uint256[] memory tokenIds = new uint256[](1); uint256[] memory quantities = new uint256[](1); Derivative[] memory derivatives = new Derivative[](1); tokenIds[0] = _tokenId; quantities[0] = _quantity; derivatives[0] = _derivative; _cancel(tokenIds, quantities, derivatives); } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) public nonReentrant { _cancel(_tokenIds, _quantities, _derivatives); } // PRIVATE FUNCTIONS struct CreatePooledLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates pooled positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _address address Address of position receiver function _createPooled(Derivative memory _derivative, uint256 _quantity, address _address) private { // Local variables CreatePooledLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is a pool require(vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_NOT_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); // Get cached margin required according to logic from Opium.SyntheticAggregator (uint256 margin, ) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: margin * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margin.mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margin.mul(_quantity)); // Since it's a pooled position, we add transferred margin to pool balance poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].add(margin.mul(_quantity)); // Mint LONG position tokens vars.tokenMinter.mint(_address, derivativeHash, _quantity); emit Created(_address, address(0), derivativeHash, _quantity); } struct CreateLocalVars { SyntheticAggregator syntheticAggregator; IDerivativeLogic derivativeLogic; IERC20 marginToken; TokenSpender tokenSpender; TokenMinter tokenMinter; } /// @notice This function creates p2p positions /// @param _derivative Derivative Derivative definition /// @param _quantity uint256 Quantity of positions to create /// @param _addresses address[2] Addresses of buyer and seller /// [0] - buyer address /// [1] - seller address function _create(Derivative memory _derivative, uint256 _quantity, address[2] memory _addresses) private { // Local variables CreateLocalVars memory vars; // Create instance of Opium.SyntheticAggregator // Create instance of Opium.IDerivativeLogic // Create instance of margin token // Create instance of Opium.TokenSpender // Create instance of Opium.TokenMinter vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); vars.derivativeLogic = IDerivativeLogic(_derivative.syntheticId); vars.marginToken = IERC20(_derivative.token); vars.tokenSpender = TokenSpender(registry.getTokenSpender()); vars.tokenMinter = TokenMinter(registry.getMinter()); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check with Opium.SyntheticAggregator if syntheticId is not a pool require(!vars.syntheticAggregator.isPool(derivativeHash, _derivative), ERROR_CORE_CANT_BE_POOL); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); // Validate input data against Derivative logic (`syntheticId`) require(vars.derivativeLogic.validateInput(_derivative), ERROR_CORE_SYNTHETIC_VALIDATION_ERROR); uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivative); // Check ERC20 tokens allowance: (margins[0] + margins[1]) * quantity // `msg.sender` must provide margin for position creation require(vars.marginToken.allowance(msg.sender, address(vars.tokenSpender)) >= margins[0].add(margins[1]).mul(_quantity), ERROR_CORE_NOT_ENOUGH_TOKEN_ALLOWANCE); // Take ERC20 tokens from msg.sender, should never revert in correct ERC20 implementation vars.tokenSpender.claimTokens(vars.marginToken, msg.sender, address(this), margins[0].add(margins[1]).mul(_quantity)); // Mint LONG and SHORT positions tokens vars.tokenMinter.mint(_addresses[0], _addresses[1], derivativeHash, _quantity); emit Created(_addresses[0], _addresses[1], derivativeHash, _quantity); } struct ExecuteAndCancelLocalVars { TokenMinter tokenMinter; OracleAggregator oracleAggregator; SyntheticAggregator syntheticAggregator; } /// @notice Executes several positions of `_tokenOwner` with different `tokenId`s /// @param _tokenOwner address Address of the owner of positions /// @param _tokenIds uint256[] `tokenId`s of positions that needs to be executed /// @param _quantities uint256[] Quantity of positions to execute for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _execute(address _tokenOwner, uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Check if execution is performed after endTime require(now > _derivatives[i].endTime, ERROR_CORE_EXECUTION_BEFORE_MATURITY_NOT_ALLOWED); // Checking whether execution is performed by `_tokenOwner` or `_tokenOwner` allowed third party executions on it's behalf require( _tokenOwner == msg.sender || IDerivativeLogic(_derivatives[i].syntheticId).thirdpartyExecutionAllowed(_tokenOwner), ERROR_CORE_SYNTHETIC_EXECUTION_WAS_NOT_ALLOWED ); // Returns payout for all positions uint256 payout = _getPayout(_derivatives[i], _tokenIds[i], _quantities[i], vars); // Transfer payout if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(_tokenOwner, payout); } // Burn executed position tokens vars.tokenMinter.burn(_tokenOwner, _tokenIds[i], _quantities[i]); emit Executed(_tokenOwner, _tokenIds[i], _quantities[i]); } } /// @notice Cancels tickers, burns positions and returns margins to positions owners in case no data were provided within `NO_DATA_CANCELLATION_PERIOD` /// @param _tokenIds uint256[] `tokenId` of positions that needs to be canceled /// @param _quantities uint256[] Quantity of positions to cancel for each `tokenId` /// @param _derivatives Derivative[] Derivative definitions for each `tokenId` function _cancel(uint256[] memory _tokenIds, uint256[] memory _quantities, Derivative[] memory _derivatives) private { require(_tokenIds.length == _quantities.length, ERROR_CORE_TOKEN_IDS_AND_QUANTITIES_LENGTH_DOES_NOT_MATCH); require(_tokenIds.length == _derivatives.length, ERROR_CORE_TOKEN_IDS_AND_DERIVATIVES_LENGTH_DOES_NOT_MATCH); // Local variables ExecuteAndCancelLocalVars memory vars; // Create instance of Opium.TokenMinter // Create instance of Opium.OracleAggregator // Create instance of Opium.SyntheticAggregator vars.tokenMinter = TokenMinter(registry.getMinter()); vars.oracleAggregator = OracleAggregator(registry.getOracleAggregator()); vars.syntheticAggregator = SyntheticAggregator(registry.getSyntheticAggregator()); for (uint256 i; i < _tokenIds.length; i++) { // Don't allow to cancel tickers with "dummy" oracleIds require(_derivatives[i].oracleId != address(0), ERROR_CORE_CANT_CANCEL_DUMMY_ORACLE_ID); // Check if cancellation is called after `NO_DATA_CANCELLATION_PERIOD` and `oracleId` didn't provided data require( _derivatives[i].endTime + NO_DATA_CANCELLATION_PERIOD <= now && !vars.oracleAggregator.hasData(_derivatives[i].oracleId, _derivatives[i].endTime), ERROR_CORE_CANCELLATION_IS_NOT_ALLOWED ); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivatives[i]); // Emit `Canceled` event only once and mark ticker as canceled if (!cancelled[derivativeHash]) { cancelled[derivativeHash] = true; emit Canceled(derivativeHash); } uint256[2] memory margins; // Get cached margin required according to logic from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = vars.syntheticAggregator.getMargin(derivativeHash, _derivatives[i]); uint256 payout; // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenIds[i]) { // Set payout to buyerPayout payout = margins[0]; // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenIds[i]) { // Set payout to sellerPayout payout = margins[1]; } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } // Transfer payout * _quantities[i] if (payout > 0) { IERC20(_derivatives[i].token).safeTransfer(msg.sender, payout.mul(_quantities[i])); } // Burn canceled position tokens vars.tokenMinter.burn(msg.sender, _tokenIds[i], _quantities[i]); } } /// @notice Calculates payout for position and gets fees /// @param _derivative Derivative Derivative definition /// @param _tokenId uint256 `tokenId` of positions /// @param _quantity uint256 Quantity of positions /// @param _vars ExecuteAndCancelLocalVars Helping local variables /// @return payout uint256 Payout for all tokens function _getPayout(Derivative memory _derivative, uint256 _tokenId, uint256 _quantity, ExecuteAndCancelLocalVars memory _vars) private returns (uint256 payout) { // Trying to getData from Opium.OracleAggregator, could be reverted // Opium allows to use "dummy" oracleIds, in this case data is set to `0` uint256 data; if (_derivative.oracleId != address(0)) { data = _vars.oracleAggregator.getData(_derivative.oracleId, _derivative.endTime); } else { data = 0; } uint256[2] memory payoutRatio; // Get payout ratio from Derivative logic // payoutRatio[0] - buyerPayout // payoutRatio[1] - sellerPayout (payoutRatio[0], payoutRatio[1]) = IDerivativeLogic(_derivative.syntheticId).getExecutionPayout(_derivative, data); // Generate hash for derivative bytes32 derivativeHash = getDerivativeHash(_derivative); // Check if ticker was canceled require(!cancelled[derivativeHash], ERROR_CORE_TICKER_WAS_CANCELLED); uint256[2] memory margins; // Get cached total margin required from Opium.SyntheticAggregator // margins[0] - buyerMargin // margins[1] - sellerMargin (margins[0], margins[1]) = _vars.syntheticAggregator.getMargin(derivativeHash, _derivative); uint256[2] memory payouts; // Calculate payouts from ratio // payouts[0] -> buyerPayout = (buyerMargin + sellerMargin) * buyerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) // payouts[1] -> sellerPayout = (buyerMargin + sellerMargin) * sellerPayoutRatio / (buyerPayoutRatio + sellerPayoutRatio) payouts[0] = margins[0].add(margins[1]).mul(payoutRatio[0]).div(payoutRatio[0].add(payoutRatio[1])); payouts[1] = margins[0].add(margins[1]).mul(payoutRatio[1]).div(payoutRatio[0].add(payoutRatio[1])); // Check if `_tokenId` is an ID of LONG position if (derivativeHash.getLongTokenId() == _tokenId) { // Check if it's a pooled position if (_vars.syntheticAggregator.isPool(derivativeHash, _derivative)) { // Pooled position payoutRatio is considered as full payout, not as payoutRatio payout = payoutRatio[0]; // Multiply payout by quantity payout = payout.mul(_quantity); // Check sufficiency of syntheticId balance in poolVaults require( poolVaults[_derivative.syntheticId][_derivative.token] >= payout , ERROR_CORE_INSUFFICIENT_POOL_BALANCE ); // Subtract paid out margin from poolVault poolVaults[_derivative.syntheticId][_derivative.token] = poolVaults[_derivative.syntheticId][_derivative.token].sub(payout); } else { // Set payout to buyerPayout payout = payouts[0]; // Multiply payout by quantity payout = payout.mul(_quantity); } // Take fees only from profit makers // Check: payout > buyerMargin * quantity if (payout > margins[0].mul(_quantity)) { // Get Opium and `syntheticId` author fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[0].mul(_quantity))); } // Check if `_tokenId` is an ID of SHORT position } else if (derivativeHash.getShortTokenId() == _tokenId) { // Set payout to sellerPayout payout = payouts[1]; // Multiply payout by quantity payout = payout.mul(_quantity); // Take fees only from profit makers // Check: payout > sellerMargin * quantity if (payout > margins[1].mul(_quantity)) { // Get Opium fees and subtract it from payout payout = payout.sub(_getFees(_vars.syntheticAggregator, derivativeHash, _derivative, payout - margins[1].mul(_quantity))); } } else { // Either portfolioId, hack or bug revert(ERROR_CORE_UNKNOWN_POSITION_TYPE); } } /// @notice Calculates `syntheticId` author and opium fees from profit makers /// @param _syntheticAggregator SyntheticAggregator Instance of Opium.SyntheticAggregator /// @param _derivativeHash bytes32 Derivative hash /// @param _derivative Derivative Derivative definition /// @param _profit uint256 payout of one position /// @return fee uint256 Opium and `syntheticId` author fee function _getFees(SyntheticAggregator _syntheticAggregator, bytes32 _derivativeHash, Derivative memory _derivative, uint256 _profit) private returns (uint256 fee) { // Get cached `syntheticId` author address from Opium.SyntheticAggregator address authorAddress = _syntheticAggregator.getAuthorAddress(_derivativeHash, _derivative); // Get cached `syntheticId` fee percentage from Opium.SyntheticAggregator uint256 commission = _syntheticAggregator.getAuthorCommission(_derivativeHash, _derivative); // Calculate fee // fee = profit * commission / COMMISSION_BASE fee = _profit.mul(commission).div(COMMISSION_BASE); // If commission is zero, finish if (fee == 0) { return 0; } // Calculate opium fee // opiumFee = fee * OPIUM_COMMISSION_PART / OPIUM_COMMISSION_BASE uint256 opiumFee = fee.mul(OPIUM_COMMISSION_PART).div(OPIUM_COMMISSION_BASE); // Calculate author fee // authorFee = fee - opiumFee uint256 authorFee = fee.sub(opiumFee); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Update feeVault for Opium team // feesVault[opium][token] += opiumFee feesVaults[opiumAddress][_derivative.token] = feesVaults[opiumAddress][_derivative.token].add(opiumFee); // Update feeVault for `syntheticId` author // feeVault[author][token] += authorFee feesVaults[authorAddress][_derivative.token] = feesVaults[authorAddress][_derivative.token].add(authorFee); } } // File: contracts/Errors/MatchingErrors.sol pragma solidity 0.5.16; contract MatchingErrors { string constant internal ERROR_MATCH_CANCELLATION_NOT_ALLOWED = "MATCH:CANCELLATION_NOT_ALLOWED"; string constant internal ERROR_MATCH_ALREADY_CANCELED = "MATCH:ALREADY_CANCELED"; string constant internal ERROR_MATCH_ORDER_WAS_CANCELED = "MATCH:ORDER_WAS_CANCELED"; string constant internal ERROR_MATCH_TAKER_ADDRESS_WRONG = "MATCH:TAKER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_ORDER_IS_EXPIRED = "MATCH:ORDER_IS_EXPIRED"; string constant internal ERROR_MATCH_SENDER_ADDRESS_WRONG = "MATCH:SENDER_ADDRESS_WRONG"; string constant internal ERROR_MATCH_SIGNATURE_NOT_VERIFIED = "MATCH:SIGNATURE_NOT_VERIFIED"; string constant internal ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES = "MATCH:NOT_ENOUGH_ALLOWED_FEES"; } // File: contracts/Lib/LibEIP712.sol pragma solidity 0.5.16; /// @title Opium.Lib.LibEIP712 contract implements the domain of EIP712 for meta transactions contract LibEIP712 { // EIP712Domain structure // name - protocol name // version - protocol version // verifyingContract - signed message verifying contract struct EIP712Domain { string name; string version; address verifyingContract; } // Calculate typehash of ERC712Domain bytes32 constant internal EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); // solhint-disable-next-line var-name-mixedcase bytes32 internal DOMAIN_SEPARATOR; // Calculate domain separator at creation constructor () public { DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256("Opium Network"), keccak256("1"), address(this) )); } /// @notice Hashes EIP712Message /// @param hashStruct bytes32 Hash of structured message /// @return result bytes32 Hash of EIP712Message function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { bytes32 domainSeparator = DOMAIN_SEPARATOR; assembly { // Load free memory pointer let memPtr := mload(64) mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header mstore(add(memPtr, 2), domainSeparator) // EIP712 domain hash mstore(add(memPtr, 34), hashStruct) // Hash of struct // Compute hash result := keccak256(memPtr, 66) } return result; } } // File: contracts/Matching/SwaprateMatch/LibSwaprateOrder.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch.LibSwaprateOrder contract implements EIP712 signed SwaprateOrder for Opium.Matching.SwaprateMatch contract LibSwaprateOrder is LibEIP712 { /** Structure of order Description should be considered from the order signer (maker) perspective syntheticId - address of derivative syntheticId oracleId - address of derivative oracleId token - address of derivative margin token makerMarginAddress - address of token that maker is willing to pay with takerMarginAddress - address of token that maker is willing to receive makerAddress - address of maker takerAddress - address of counterparty (taker). If zero address, then taker could be anyone senderAddress - address which is allowed to settle the order on-chain. If zero address, then anyone could settle relayerAddress - address of the relayer fee recipient affiliateAddress - address of the affiliate fee recipient feeTokenAddress - address of token which is used for fees endTime - timestamp of derivative maturity quantity - quantity of positions maker wants to receive partialFill - whether maker allows partial fill of it's order param0...param9 - additional params to pass it to syntheticId relayerFee - amount of fee in feeToken that should be paid to relayer affiliateFee - amount of fee in feeToken that should be paid to affiliate nonce - unique order ID signature - Signature of EIP712 message. Not used in hash, but then set for order processing purposes */ struct SwaprateOrder { address syntheticId; address oracleId; address token; address makerAddress; address takerAddress; address senderAddress; address relayerAddress; address affiliateAddress; address feeTokenAddress; uint256 endTime; uint256 quantity; uint256 partialFill; uint256 param0; uint256 param1; uint256 param2; uint256 param3; uint256 param4; uint256 param5; uint256 param6; uint256 param7; uint256 param8; uint256 param9; uint256 relayerFee; uint256 affiliateFee; uint256 nonce; // Not used in hash bytes signature; } // Calculate typehash of Order bytes32 constant internal EIP712_ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "address syntheticId,", "address oracleId,", "address token,", "address makerAddress,", "address takerAddress,", "address senderAddress,", "address relayerAddress,", "address affiliateAddress,", "address feeTokenAddress,", "uint256 endTime,", "uint256 quantity,", "uint256 partialFill,", "uint256 param0,", "uint256 param1,", "uint256 param2,", "uint256 param3,", "uint256 param4,", "uint256 param5,", "uint256 param6,", "uint256 param7,", "uint256 param8,", "uint256 param9,", "uint256 relayerFee,", "uint256 affiliateFee,", "uint256 nonce", ")" )); /// @notice Hashes the order /// @param _order SwaprateOrder Order to hash /// @return hash bytes32 Order hash function hashOrder(SwaprateOrder memory _order) public pure returns (bytes32 hash) { hash = keccak256( abi.encodePacked( abi.encodePacked( EIP712_ORDER_TYPEHASH, uint256(_order.syntheticId), uint256(_order.oracleId), uint256(_order.token), uint256(_order.makerAddress), uint256(_order.takerAddress), uint256(_order.senderAddress), uint256(_order.relayerAddress), uint256(_order.affiliateAddress), uint256(_order.feeTokenAddress) ), abi.encodePacked( _order.endTime, _order.quantity, _order.partialFill ), abi.encodePacked( _order.param0, _order.param1, _order.param2, _order.param3, _order.param4 ), abi.encodePacked( _order.param5, _order.param6, _order.param7, _order.param8, _order.param9 ), abi.encodePacked( _order.relayerFee, _order.affiliateFee, _order.nonce ) ) ); } /// @notice Verifies order signature /// @param _hash bytes32 Hash of the order /// @param _signature bytes Signature of the order /// @param _address address Address of the order signer /// @return bool Returns whether `_signature` is valid and was created by `_address` function verifySignature(bytes32 _hash, bytes memory _signature, address _address) internal view returns (bool) { require(_signature.length == 65, "ORDER:INVALID_SIGNATURE_LENGTH"); bytes32 digest = hashEIP712Message(_hash); address recovered = retrieveAddress(digest, _signature); return _address == recovered; } /// @notice Helping function to recover signer address /// @param _hash bytes32 Hash for signature /// @param _signature bytes Signature /// @return address Returns address of signature creator function retrieveAddress(bytes32 _hash, bytes memory _signature) private pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(_hash, v, r, s); } } } // File: contracts/Matching/SwaprateMatch/SwaprateMatchBase.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatchBase contract implements logic for order validation and cancelation contract SwaprateMatchBase is MatchingErrors, LibSwaprateOrder, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using LibPosition for bytes32; using SafeERC20 for IERC20; // Emmitted when order was canceled event Canceled(bytes32 orderHash); // Canceled orders // This mapping holds hashes of canceled orders // canceled[orderHash] => canceled mapping (bytes32 => bool) public canceled; // Verified orders // This mapping holds hashes of verified orders to verify only once // verified[orderHash] => verified mapping (bytes32 => bool) public verified; // Vaults for fees // This mapping holds balances of relayers and affiliates fees to withdraw // balances[feeRecipientAddress][tokenAddress] => balances mapping (address => mapping (address => uint256)) public balances; // Keeps whether fee was already taken mapping (bytes32 => bool) public feeTaken; /// @notice Calling this function maker of the order could cancel it on-chain /// @param _order SwaprateOrder function cancel(SwaprateOrder memory _order) public { require(msg.sender == _order.makerAddress, ERROR_MATCH_CANCELLATION_NOT_ALLOWED); bytes32 orderHash = hashOrder(_order); require(!canceled[orderHash], ERROR_MATCH_ALREADY_CANCELED); canceled[orderHash] = true; emit Canceled(orderHash); } /// @notice Function to withdraw fees from orders for relayer and affiliates /// @param _token IERC20 Instance of token to withdraw function withdraw(IERC20 _token) public nonReentrant { uint256 balance = balances[msg.sender][address(_token)]; balances[msg.sender][address(_token)] = 0; _token.safeTransfer(msg.sender, balance); } /// @notice This function checks whether order was canceled /// @param _hash bytes32 Hash of the order function validateNotCanceled(bytes32 _hash) internal view { require(!canceled[_hash], ERROR_MATCH_ORDER_WAS_CANCELED); } /// @notice This function validates takerAddress of _leftOrder. It should match either with _rightOrder.makerAddress or be set to zero address /// @param _leftOrder SwaprateOrder Left order /// @param _rightOrder SwaprateOrder Right order function validateTakerAddress(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder) pure internal { require( _leftOrder.takerAddress == address(0) || _leftOrder.takerAddress == _rightOrder.makerAddress, ERROR_MATCH_TAKER_ADDRESS_WRONG ); } /// @notice This function validates whether sender address equals to `msg.sender` or set to zero address /// @param _order SwaprateOrder function validateSenderAddress(SwaprateOrder memory _order) internal view { require( _order.senderAddress == address(0) || _order.senderAddress == msg.sender, ERROR_MATCH_SENDER_ADDRESS_WRONG ); } /// @notice This function validates order signature if not validated before /// @param orderHash bytes32 Hash of the order /// @param _order SwaprateOrder function validateSignature(bytes32 orderHash, SwaprateOrder memory _order) internal { if (verified[orderHash]) { return; } bool result = verifySignature(orderHash, _order.signature, _order.makerAddress); require(result, ERROR_MATCH_SIGNATURE_NOT_VERIFIED); verified[orderHash] = true; } /// @notice This function is responsible for taking relayer and affiliate fees, if they were not taken already /// @param _orderHash bytes32 Hash of the order /// @param _order Order Order itself function takeFees(bytes32 _orderHash, SwaprateOrder memory _order) internal { // Check if fee was already taken if (feeTaken[_orderHash]) { return; } // Check if feeTokenAddress is not set to zero address if (_order.feeTokenAddress == address(0)) { return; } // Calculate total amount of fees needs to be transfered uint256 fees = _order.relayerFee.add(_order.affiliateFee); // If total amount of fees is non-zero if (fees == 0) { return; } // Create instance of fee token IERC20 feeToken = IERC20(_order.feeTokenAddress); // Create instance of TokenSpender TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Check if user has enough token approval to pay the fees require(feeToken.allowance(_order.makerAddress, address(tokenSpender)) >= fees, ERROR_MATCH_NOT_ENOUGH_ALLOWED_FEES); // Transfer fee tokenSpender.claimTokens(feeToken, _order.makerAddress, address(this), fees); // Get opium address address opiumAddress = registry.getOpiumAddress(); // Add commission to relayer balance, or to opium balance if relayer is not set if (_order.relayerAddress != address(0)) { balances[_order.relayerAddress][_order.feeTokenAddress] = balances[_order.relayerAddress][_order.feeTokenAddress].add(_order.relayerFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.relayerFee); } // Add commission to affiliate balance, or to opium balance if affiliate is not set if (_order.affiliateAddress != address(0)) { balances[_order.affiliateAddress][_order.feeTokenAddress] = balances[_order.affiliateAddress][_order.feeTokenAddress].add(_order.affiliateFee); } else { balances[opiumAddress][_order.feeTokenAddress] = balances[opiumAddress][_order.feeTokenAddress].add(_order.affiliateFee); } // Mark the fee of token as taken feeTaken[_orderHash] = true; } /// @notice Helper to get minimal of two integers /// @param _a uint256 First integer /// @param _b uint256 Second integer /// @return uint256 Minimal integer function min(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: contracts/Matching/SwaprateMatch/SwaprateMatch.sol pragma solidity 0.5.16; /// @title Opium.Matching.SwaprateMatch contract implements create() function to settle a pair of orders and create derivatives for order makers contract SwaprateMatch is SwaprateMatchBase, LibDerivative { // Orders filled quantity // This mapping holds orders filled quantity // filled[orderHash] => filled mapping (bytes32 => uint256) public filled; /// @notice Calls constructors of super-contracts /// @param _registry address Address of Opium.registry constructor (address _registry) public UsingRegistry(_registry) {} /// @notice This function receives left and right orders, derivative related to it /// @param _leftOrder Order /// @param _rightOrder Order /// @param _derivative Derivative Data of derivative for validation and calculation purposes function create(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) public nonReentrant { // New deals must not offer tokenIds require( _leftOrder.syntheticId == _rightOrder.syntheticId, "MATCH:NOT_CREATION" ); // Check if it's not pool require(!IDerivativeLogic(_derivative.syntheticId).isPool(), "MATCH:CANT_BE_POOL"); // Validate taker if set validateTakerAddress(_leftOrder, _rightOrder); validateTakerAddress(_rightOrder, _leftOrder); // Validate sender if set validateSenderAddress(_leftOrder); validateSenderAddress(_rightOrder); // Validate if was canceled // orderHashes[0] - leftOrderHash // orderHashes[1] - rightOrderHash bytes32[2] memory orderHashes; orderHashes[0] = hashOrder(_leftOrder); validateNotCanceled(orderHashes[0]); validateSignature(orderHashes[0], _leftOrder); orderHashes[1] = hashOrder(_rightOrder); validateNotCanceled(orderHashes[1]); validateSignature(orderHashes[1], _rightOrder); // Calculate derivative hash and get margin // margins[0] - leftMargin // margins[1] - rightMargin (uint256[2] memory margins, ) = _calculateDerivativeAndGetMargin(_derivative); // Calculate and validate availabilities of orders and fill them uint256 fillable = _checkFillability(orderHashes[0], _leftOrder, orderHashes[1], _rightOrder); // Validate derivative parameters with orders _verifyDerivative(_leftOrder, _rightOrder, _derivative); // Take fees takeFees(orderHashes[0], _leftOrder); takeFees(orderHashes[1], _rightOrder); // Send margin to Core _distributeFunds(_leftOrder, _rightOrder, _derivative, margins, fillable); // Settle contracts Core(registry.getCore()).create(_derivative, fillable, [_leftOrder.makerAddress, _rightOrder.makerAddress]); } // PRIVATE FUNCTIONS /// @notice Calculates derivative hash and gets margin /// @param _derivative Derivative /// @return margins uint256[2] left and right margin /// @return derivativeHash bytes32 Hash of the derivative function _calculateDerivativeAndGetMargin(Derivative memory _derivative) private returns (uint256[2] memory margins, bytes32 derivativeHash) { // Calculate derivative related data for validation derivativeHash = getDerivativeHash(_derivative); // Get cached total margin required according to logic // margins[0] - leftMargin // margins[1] - rightMargin (margins[0], margins[1]) = SyntheticAggregator(registry.getSyntheticAggregator()).getMargin(derivativeHash, _derivative); } /// @notice Calculate and validate availabilities of orders and fill them /// @param _leftOrderHash bytes32 /// @param _leftOrder SwaprateOrder /// @param _rightOrderHash bytes32 /// @param _rightOrder SwaprateOrder /// @return fillable uint256 function _checkFillability(bytes32 _leftOrderHash, SwaprateOrder memory _leftOrder, bytes32 _rightOrderHash, SwaprateOrder memory _rightOrder) private returns (uint256 fillable) { // Calculate availabilities of orders uint256 leftAvailable = _leftOrder.quantity.sub(filled[_leftOrderHash]); uint256 rightAvailable = _rightOrder.quantity.sub(filled[_rightOrderHash]); require(leftAvailable != 0 && rightAvailable !=0, "MATCH:NO_AVAILABLE"); // We could only fill minimum available of both counterparties fillable = min(leftAvailable, rightAvailable); // Check fillable with order conditions about partial fill requirements if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 0) { require(_leftOrder.quantity == _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 0 && _rightOrder.partialFill == 1) { require(_leftOrder.quantity <= rightAvailable, "MATCH:FULL_FILL_NOT_POSSIBLE"); } else if (_leftOrder.partialFill == 1 && _rightOrder.partialFill == 0) { require(leftAvailable >= _rightOrder.quantity, "MATCH:FULL_FILL_NOT_POSSIBLE"); } // Update filled filled[_leftOrderHash] = filled[_leftOrderHash].add(fillable); filled[_rightOrderHash] = filled[_rightOrderHash].add(fillable); } /// @notice Validate derivative parameters with orders /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative function _verifyDerivative(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative) private pure { string memory orderError = "MATCH:DERIVATIVE_PARAM_IS_WRONG"; // Validate derivative endTime require( _derivative.endTime == _leftOrder.endTime && _derivative.endTime == _rightOrder.endTime, orderError ); // Validate derivative syntheticId require( _derivative.syntheticId == _leftOrder.syntheticId && _derivative.syntheticId == _rightOrder.syntheticId, orderError ); // Validate derivative oracleId require( _derivative.oracleId == _leftOrder.oracleId && _derivative.oracleId == _rightOrder.oracleId, orderError ); // Validate derivative token require( _derivative.token == _leftOrder.token && _derivative.token == _rightOrder.token, orderError ); // Validate derivative params require(_derivative.params.length >= 20, "MATCH:DERIVATIVE_PARAMS_LENGTH_IS_WRONG"); // Validate left order params require(_leftOrder.param0 == _derivative.params[0], orderError); require(_leftOrder.param1 == _derivative.params[1], orderError); require(_leftOrder.param2 == _derivative.params[2], orderError); require(_leftOrder.param3 == _derivative.params[3], orderError); require(_leftOrder.param4 == _derivative.params[4], orderError); require(_leftOrder.param5 == _derivative.params[5], orderError); require(_leftOrder.param6 == _derivative.params[6], orderError); require(_leftOrder.param7 == _derivative.params[7], orderError); require(_leftOrder.param8 == _derivative.params[8], orderError); require(_leftOrder.param9 == _derivative.params[9], orderError); // Validate right order params require(_rightOrder.param0 == _derivative.params[10], orderError); require(_rightOrder.param1 == _derivative.params[11], orderError); require(_rightOrder.param2 == _derivative.params[12], orderError); require(_rightOrder.param3 == _derivative.params[13], orderError); require(_rightOrder.param4 == _derivative.params[14], orderError); require(_rightOrder.param5 == _derivative.params[15], orderError); require(_rightOrder.param6 == _derivative.params[16], orderError); require(_rightOrder.param7 == _derivative.params[17], orderError); require(_rightOrder.param8 == _derivative.params[18], orderError); require(_rightOrder.param9 == _derivative.params[19], orderError); } /// @notice Distributes funds to core /// @param _leftOrder SwaprateOrder /// @param _rightOrder SwaprateOrder /// @param _derivative Derivative /// @param margins uint256[2] left and right margin /// @param _fillable uint256 How many positions are fillable function _distributeFunds(SwaprateOrder memory _leftOrder, SwaprateOrder memory _rightOrder, Derivative memory _derivative, uint256[2] memory margins, uint256 _fillable) private { IERC20 marginToken = IERC20(_derivative.token); TokenSpender tokenSpender = TokenSpender(registry.getTokenSpender()); // Transfer margin from left to Match and send to Core if (margins[0] != 0) { // Check allowance for margins require(marginToken.allowance(_leftOrder.makerAddress, address(tokenSpender)) >= margins[0].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from buyer to Match tokenSpender.claimTokens(marginToken, _leftOrder.makerAddress, address(this), margins[0].mul(_fillable)); } // Transfer margin from right to Match and send to Core if (margins[1] != 0) { // Check allowance for premiums + margin require(marginToken.allowance(_rightOrder.makerAddress, address(tokenSpender)) >= margins[1].mul(_fillable), "MATCH:NOT_ENOUGH_ALLOWED_MARGIN"); // Transfer margins from seller to Match tokenSpender.claimTokens(marginToken, _rightOrder.makerAddress, address(this), margins[1].mul(_fillable)); } if (margins[0].add(margins[1]) != 0) { // Approve margin to Core for derivative creation require(marginToken.approve(address(tokenSpender), margins[0].add(margins[1]).mul(_fillable)), "MATCH:COULDNT_APPROVE_MARGIN_FOR_CORE"); } } }
Initializes ticker, if was not initialized and returns `syntheticId` author commission from cache _derivativeHash bytes32 Hash of derivative _derivative Derivative Derivative itself return commission uint256 Synthetic author commission Initialize derivative if wasn't initialized before
function getAuthorCommission(bytes32 _derivativeHash, Derivative memory _derivative) public nonReentrant returns (uint256 commission) { _initDerivative(_derivativeHash, _derivative); commission = commissionByHash[_derivativeHash]; }
1,368,094
./partial_match/1/0x74a954Fe4f5456CF2769D7E77dee9EBb55c258ED/sources/ERC4626Upgradeable.sol
See {IERC4626-withdraw}. /
function withdraw( uint256 assets, address receiver, address owner ) public virtual override returns (uint256) { require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max"); uint256 shares = previewWithdraw(assets); _withdraw(_msgSender(), receiver, owner, assets, shares); return shares; }
2,849,051
pragma solidity =0.5.12; import "./interfaces/IAirdropHubV1.sol"; import "./interfaces/ITRC20.sol"; import "./interfaces/ITRC20Burnable.sol"; import "./libraries/SafeMath.sol"; contract AirdropV1 { using SafeMath for uint256; event Staked(address indexed staker, uint256 indexed amount); event Unstaked(address indexed staker, uint256 indexed amount); event AirdropReward(address indexed staker, uint256 indexed amount); event ReferralReward( address indexed referrer, address indexed referred, uint256 indexed amount ); address public hub; address public stakeToken; address public airdropToken; uint256 public airdropAmount; uint256 public snapshotTime; uint256 public referralRate; uint256 public rewardMultiplier; bool public initialized; bool public remainingBurnt; uint256 public currentStakerCount; uint256 public totalStakedAmount; mapping(address => uint256) public stakedAmounts; bool public snapshotTaken; uint256 public snapshotedStakerCount; uint256 public snapshotedStakedAmount; uint256 public snapshotedStakeTokenSupply; uint256 public accuAirdropReward; uint256 public accuReferralReward; uint256 public constant PERCENTAGE_100 = 10000; uint256 public constant MAX_REFERRAL_RATE = 10000; // Hard-coded upper limit for referral rate: 100% uint256 public constant MAX_REWARD_MULTIPLIER = 100000; // Hard-coded upper limit for reward multiplier: 1000% modifier onlyHub() { require(msg.sender == hub, "Airdrop: not hub"); _; } modifier onlyOwner() { require(msg.sender == IAirdropHubV1(hub).owner(), "Airdrop: not owner"); _; } modifier onlyInitialized() { require(initialized, "Airdrop: not initialized"); _; } modifier onlyEnded() { require(block.timestamp >= snapshotTime, "Airdrop: not ended"); _; } modifier onlyNotEnded() { require(block.timestamp < snapshotTime, "Airdrop: ended"); _; } modifier onlyNoStaker() { require(currentStakerCount == 0, "Airdrop: not zero staker"); _; } constructor( uint256 _airdropAmount, uint256 _snapshotTime, uint256 _referralRate, uint256 _rewardMultiplier ) public { require(_airdropAmount > 0, "Airdrop: zero amount"); require( _snapshotTime > block.timestamp, "Airdrop: snapshot time in the past" ); require( _referralRate <= MAX_REFERRAL_RATE, "Airdrop: referral rate out of range" ); require( _rewardMultiplier <= MAX_REWARD_MULTIPLIER, "Airdrop: reward multiplier out of range" ); hub = msg.sender; stakeToken = IAirdropHubV1(msg.sender).stakeToken(); airdropToken = IAirdropHubV1(msg.sender).airdropToken(); airdropAmount = _airdropAmount; snapshotTime = _snapshotTime; referralRate = _referralRate; rewardMultiplier = _rewardMultiplier; } /** * @dev We're marking the fallback function as payable so that we can test it with * tools from Ethereum. Doing this does NOT make it easier to send funds by mistake. * * On Tron, simple TRX transfers do not trigger contract code, as opposed to Ethereum * where the fallback function is invoked. So making the fallback function non-payable * won't stop users from accidentally sending TRX. It's necessary to mark the fallback * payable to mock this behavior on Ethereum. */ function() external payable {} /** * @dev This funtion is called by hub to verify that the amount of airdropToken * is already available in the contract. */ function initialize() external onlyHub { require(!initialized, "Airdrop: not initialized"); require( ITRC20(airdropToken).balanceOf(address(this)) == airdropAmount, "Airdrop: airdrop amount mismatch" ); initialized = true; } /** * @dev Stake the entire remaining token balance. Cannot be called after snapshot time. */ function stake(address referrer) external onlyInitialized onlyNotEnded { _stake(msg.sender, ITRC20(stakeToken).balanceOf(msg.sender), referrer); } /** * @dev Stake the specified amount of tokens. Cannot be called after snapshot time. */ function stake(uint256 amount, address referrer) external onlyInitialized onlyNotEnded { _stake(msg.sender, amount, referrer); } /** * @dev Unstake all staked tokens. * * Users can unstake at any time, including before the snapshot time. */ function unstake() external onlyInitialized { _unstake(msg.sender, stakedAmounts[msg.sender], true); } /** * @dev Unstake a specified amount of tokens. This function can only be called * before snapshot. After snapshot users can only unstake all tokens. There's no * reason to partially unstake after snapshot anyways. */ function unstake(uint256 amount) external onlyInitialized onlyNotEnded { _unstake(msg.sender, amount, true); } /** * @dev Unstake all staked tokens, but without getting airdrop rewards. * * This is en emergency exit for getting the staked tokens back just in case there's * something wrong with the reward calculation. There shouldn't be any but we're putting * it here just to be safe. * * This can only be voluntarily done by the staker. The contract owner cannot force a staker * to unstake without reward (there's no `unstakeForWithoutReward`). */ function unstakeWithoutReward() external onlyInitialized { _unstake(msg.sender, stakedAmounts[msg.sender], false); } /** * @dev Return the staked tokens to stakers along with airdrop rewards if they * forget to do so. * * In principle we shouldn't even care whether users unstake or not. However, * since some functions require all stakers to have exited to work, this function * is put in place. */ function unstakeFor(address staker) external onlyOwner onlyInitialized onlyEnded { _unstake(staker, stakedAmounts[staker], true); } /** * @dev Unstake all staked tokens. See `unstake()` on AirdropHub for details. */ function unstakeFromHub(address staker) external onlyInitialized onlyHub { _unstake(staker, stakedAmounts[staker], true); } /** * @dev This function can be called by anyone after snapshot time is reached. Presumably * it doesn't need to be called at all as a snapshot will be automatically taken when anyone * unstakes after snapshot time. It's put here just in case no one unstakes (which is unlikely). */ function takeSnapshot() external onlyInitialized onlyEnded { require(!snapshotTaken, "Airdrop: snapshot taken"); snapshotTaken = true; snapshotedStakerCount = currentStakerCount; snapshotedStakedAmount = totalStakedAmount; snapshotedStakeTokenSupply = ITRC20(stakeToken).totalSupply(); } /** * @dev This function is for withdrawing TRX from the contract in case someone * accidentally sends TRX to the address. In Ethereum we can mostly avoid this * making the contract non-payable, but that doesn't work in Tron as a normal * transfer won't trigger any contract code (not even the fallback function). * * When this happens the team will withdraw TRX and return to the original sender. * * This method does NOT need to be marked `onlyNoStaker` because stakers would * never deposit TRX. There's no risk to stakers' funds. */ function withdrawTrx(uint256 amount) external onlyOwner onlyInitialized { msg.sender.transfer(amount); } /** * @dev This function is for withdrawing any TRC20 tokens from the contract in case * someone sends tokens directly to the contract without using the stake() function. * * When this happens the team will withdraw the tokens and return to the original sender. * * Note that since this function is marked with `onlyNoStaker`, it's only callable when * all stakers have withdrawan their staked tokens. Stakers' funds are safe. It's NOT * possible for the contract owner to withdraw staked tokens. */ function withdrawTrc20(address token, uint256 amount) external onlyOwner onlyInitialized onlyNoStaker { ITRC20(token).transfer(msg.sender, amount); } /** * @dev This function is used for burning airdrop tokens left. For this to work, airdropToken * must implement ITRC20Burnable. */ function burn() external onlyOwner onlyInitialized onlyEnded onlyNoStaker { require(!remainingBurnt, "Airdrop: already burnt"); remainingBurnt = true; ITRC20Burnable(airdropToken).burn( airdropAmount.sub(accuAirdropReward).sub(accuReferralReward) ); } function _stake( address staker, uint256 amount, address referrer ) private { require(amount > 0, "Airdrop: zero amount"); uint256 stakedAmountBefore = stakedAmounts[staker]; // Update state stakedAmounts[staker] = stakedAmountBefore.add(amount); totalStakedAmount = totalStakedAmount.add(amount); if (stakedAmountBefore == 0) { currentStakerCount = currentStakerCount.add(1); } // Transfer stakeToken IAirdropHubV1(hub).transferFrom(staker, amount); // Build referral if referrer is not empty if (referrer != address(0)) IAirdropHubV1(hub).registerReferral(referrer, staker); emit Staked(staker, amount); } function _unstake( address staker, uint256 amount, bool withReward ) private { require(amount > 0, "Airdrop: zero amount"); // No need to check balance sufficiency as `sub` will throw anyways uint256 userStakedAmountBefore = stakedAmounts[staker]; uint256 userStakedAmountAfter = userStakedAmountBefore.sub(amount); uint256 totalStakedAmountBefore = totalStakedAmount; // Update state stakedAmounts[staker] = userStakedAmountAfter; totalStakedAmount = totalStakedAmountBefore.sub(amount); if (userStakedAmountAfter == 0) { currentStakerCount = currentStakerCount.sub(1); } // Return the staked token to user first require( ITRC20(stakeToken).transfer(staker, amount), "Airdrop: TRC20 trnasfer failed" ); emit Unstaked(staker, amount); // Settle the airdrop reward if (withReward && block.timestamp >= snapshotTime) { // It should only be possible to unstake all after snapshot time assert(userStakedAmountAfter == 0); // Take snapshot first if not already taken if (!snapshotTaken) { snapshotTaken = true; snapshotedStakerCount = currentStakerCount.add(1); snapshotedStakedAmount = totalStakedAmountBefore; snapshotedStakeTokenSupply = ITRC20(stakeToken).totalSupply(); } uint256 airdropReward = userStakedAmountBefore .mul(airdropAmount) .mul(rewardMultiplier) .div(snapshotedStakeTokenSupply) .div(PERCENTAGE_100); // It's possible that reward is zero if the staked amount is too small if (airdropReward > 0) { accuAirdropReward = accuAirdropReward.add(airdropReward); require( ITRC20(airdropToken).transfer(staker, airdropReward), "Airdrop: TRC20 trnasfer failed" ); emit AirdropReward(staker, airdropReward); // Settle referral reward address referrer = IAirdropHubV1(hub).referrersByReferred(staker); if (referrer != address(0)) { uint256 referralReward = airdropReward .mul(referralRate) .div(PERCENTAGE_100); if (referralReward > 0) { accuReferralReward = accuReferralReward.add( referralReward ); require( ITRC20(airdropToken).transfer( referrer, referralReward ), "Airdrop: TRC20 trnasfer failed" ); emit ReferralReward(referrer, staker, referralReward); IAirdropHubV1(hub).addReferralReward( referrer, referralReward ); } } } } } }
No need to check balance sufficiency as `sub` will throw anyways Update state Settle the airdrop reward It should only be possible to unstake all after snapshot time Take snapshot first if not already taken It's possible that reward is zero if the staked amount is too small Settle referral reward
function _unstake( address staker, uint256 amount, bool withReward ) private { require(amount > 0, "Airdrop: zero amount"); uint256 userStakedAmountBefore = stakedAmounts[staker]; uint256 userStakedAmountAfter = userStakedAmountBefore.sub(amount); uint256 totalStakedAmountBefore = totalStakedAmount; stakedAmounts[staker] = userStakedAmountAfter; totalStakedAmount = totalStakedAmountBefore.sub(amount); if (userStakedAmountAfter == 0) { currentStakerCount = currentStakerCount.sub(1); } ITRC20(stakeToken).transfer(staker, amount), "Airdrop: TRC20 trnasfer failed" ); emit Unstaked(staker, amount); if (withReward && block.timestamp >= snapshotTime) { assert(userStakedAmountAfter == 0); if (!snapshotTaken) { snapshotTaken = true; snapshotedStakerCount = currentStakerCount.add(1); snapshotedStakedAmount = totalStakedAmountBefore; snapshotedStakeTokenSupply = ITRC20(stakeToken).totalSupply(); } uint256 airdropReward = userStakedAmountBefore .mul(airdropAmount) .mul(rewardMultiplier) .div(snapshotedStakeTokenSupply) .div(PERCENTAGE_100); if (airdropReward > 0) { accuAirdropReward = accuAirdropReward.add(airdropReward); require( ITRC20(airdropToken).transfer(staker, airdropReward), "Airdrop: TRC20 trnasfer failed" ); emit AirdropReward(staker, airdropReward); address referrer = IAirdropHubV1(hub).referrersByReferred(staker); if (referrer != address(0)) { uint256 referralReward = airdropReward .mul(referralRate) .div(PERCENTAGE_100); if (referralReward > 0) { accuReferralReward = accuReferralReward.add( referralReward ); require( ITRC20(airdropToken).transfer( referrer, referralReward ), "Airdrop: TRC20 trnasfer failed" ); emit ReferralReward(referrer, staker, referralReward); IAirdropHubV1(hub).addReferralReward( referrer, referralReward ); } } } } }
12,769,284
./full_match/1/0x5A01592A2a4acfE2949f766EF67F4f7d04bE4ac0/sources/contracts/core/prize-pool/PrizePool.sol
@inheritdoc IPrizePool
function getClaimableReward( address _user ) external view override returns (uint256) { UserStakeInfo memory userInfo = userStakeInfo[_user]; return (userInfo.reward + ((ticket.balanceOf(_user) * _getUpdatedRewardPerShare()) - userInfo.former)) / ACCURACY; }
9,746,585
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.3; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || !_initialized, 'Initializable: contract is already initialized' ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.3; 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import './IERC20Upgradeable.sol'; import './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 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, 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ 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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, 'ERC20: transfer amount exceeds allowance' ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, 'ERC20: decreased allowance below zero' ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, 'ERC20: transfer amount exceeds balance'); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: mint to the zero address'); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), 'ERC20: burn from the zero address'); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, 'ERC20: burn amount exceeds balance'); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 pragma solidity ^0.8.3; import './openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; contract WhnsTokenV1 is ERC20Upgradeable { struct MintArgs { address to; uint256 amount; } /** * @dev The address with permission to mint new tokens */ address public minter; /** * @dev Tracking for used redeem tokens. */ mapping(bytes32 => bool) public isRedeemTokenUsed; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) internal _supportedInterfaces; event TokensRedeemed( bytes32 indexed redeemToken, address indexed from, uint256 amount ); function initialize(address _minter) public initializer { __ERC20_init('Wrapped HNS', 'WHNS'); minter = _minter; _supportedInterfaces[this.supportsInterface.selector] = true; // ERC165 itself _supportedInterfaces[0x36372b07] = true; // ERC20 _supportedInterfaces[ this.name.selector ^ this.symbol.selector ^ this.decimals.selector ] = true; // ERC20 metadata _supportedInterfaces[this.name.selector] = true; _supportedInterfaces[this.symbol.selector] = true; _supportedInterfaces[this.decimals.selector] = true; } function decimals() public pure override returns (uint8) { return 6; } /** * @dev Mint tokens to an address. Can only be called by the recognized minter. * * @param _to The address to mint to * @param _amount The amount (in dollarydoos) to mint */ function mint(address _to, uint256 _amount) external { require(msg.sender == minter); _mint(_to, _amount); } /** * @dev Mint tokens to a set of addresses. Can only be called by the recognized * minter. * * @param _mints The set of {to: address, amount: uint256} pairs */ function batchMint(MintArgs[] calldata _mints) external { require(msg.sender == minter); for (uint256 i = 0; i < _mints.length; i++) { _mint(_mints[i].to, _mints[i].amount); } } /** * @dev Allows a token holder to redeem tokens to real HNS in a Namebase account. * A particular redeem token can only be used once. * * @param _amount the number of dollarydoos to redeem * @param _redeemToken 32 bytes to identify the redemption, provided by Namebase */ function redeem(uint256 _amount, bytes32 _redeemToken) external { require(isRedeemTokenUsed[_redeemToken] == false); isRedeemTokenUsed[_redeemToken] = true; _burn(msg.sender, _amount); emit TokensRedeemed(_redeemToken, msg.sender, _amount); } /** * @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) { return _supportedInterfaces[_interfaceId]; } }
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; }
6,967,935
./full_match/1/0x63a01783E8F100890Faa32cE3850486A5410E193/sources/contracts/MorphicBeast.sol
the total price of token amounts which the sender will mint
function price(uint256 _count) public pure returns (uint256) { return PRICE.mul(_count); }
9,634,113
// File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.7.5; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.7.5; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.7.5; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.7.5; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner()); _; } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/BridgeOperationsStorage.sol pragma solidity 0.7.5; /** * @title BridgeOperationsStorage * @dev Functionality for storing processed bridged operations. */ abstract contract BridgeOperationsStorage is EternalStorage { /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.7.5; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @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 OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); _; } /** * @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner. */ modifier onlyRelevantSender() { (bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)); require( !isProxy || // covers usage without calling through storage proxy (returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/interfaces/IAMB.sol pragma solidity 0.7.5; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function requireToConfirmMessage( address _contract, bytes calldata _data, uint256 _gas ) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.7.5; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { _onlyMediator(); _; } /** * @dev Internal function for reducing onlyMediator modifier bytecode overhead. */ function _onlyMediator() internal view { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view virtual returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(Address.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/FailedMessagesProcessor.sol pragma solidity 0.7.5; /** * @title FailedMessagesProcessor * @dev Functionality for fixing failed bridging operations. */ abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(_messageId, token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } function executeActionOnFixedTokens( bytes32 _messageId, address _token, address _recipient, uint256 _value ) internal virtual; } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/NFTBridgeLimits.sol pragma solidity 0.7.5; /** * @title NFTBridgeLimits * @dev Functionality for keeping track of bridging limits for multiple ERC721 tokens. */ abstract contract NFTBridgeLimits is Ownable { // token == 0x00..00 represents default limits for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token was already bridged. */ function isTokenRegistered(address _token) public view virtual returns (bool); /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @return true, if specified amount can be bridged. */ function withinLimit(address _token) public view returns (bool) { return dailyLimit(address(0)) > 0 && dailyLimit(_token) > totalSpentPerDay(_token, getCurrentDay()); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token) public view returns (bool) { return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) > totalExecutedPerDay(_token, getCurrentDay()); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(_token == address(0) || isTokenRegistered(_token)); _setDailyLimit(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(_token == address(0) || isTokenRegistered(_token)); _setExecutionDailyLimit(_token, _dailyLimit); } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. */ function addTotalSpentPerDay(address _token) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, getCurrentDay()))] += 1; } /** * @dev Internal function for adding executed amount for some token. * @param _token address of the token contract. */ function addTotalExecutedPerDay(address _token) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, getCurrentDay()))] += 1; } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _dailyLimit daily limit for the given token. */ function _setDailyLimit(address _token, uint256 _dailyLimit) internal { uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _dailyLimit daily execution limit for the given token. */ function _setExecutionDailyLimit(address _token, uint256 _dailyLimit) internal { uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } } // File: @openzeppelin/contracts/introspection/IERC165.sol pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.7.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: contracts/interfaces/IBurnableMintableERC721Token.sol pragma solidity 0.7.5; interface IBurnableMintableERC721Token is IERC721 { function mint(address _to, uint256 _tokeId) external; function burn(uint256 _tokenId) external; function setTokenURI(uint256 _tokenId, string calldata _tokenURI) external; } // File: contracts/libraries/Bytes.sol pragma solidity 0.7.5; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 20 bytes. * A case when _bytes has length less than 20 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to address type * @return addr address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.7.5; contract ReentrancyGuard { function lock() internal view returns (bool res) { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock")) } } function setLock(bool _lock) internal { assembly { // Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))], // since solidity mapping introduces another level of addressing, such slot change is safe // for temporary variables which are cleared at the end of the call execution. sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock")) } } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/ERC721Relayer.sol pragma solidity 0.7.5; /** * @title ERC721Relayer * @dev Functionality for bridging multiple tokens to the other side of the bridge. */ abstract contract ERC721Relayer is BasicAMBMediator, ReentrancyGuard { /** * @dev ERC721 transfer callback function. * @param _from address of token sender. * @param _tokenId id of the transferred token. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onERC721Received( address, address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4) { if (!lock()) { bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, chooseReceiver(_from, _data), _tokenId); } return msg.sig; } /** * @dev Initiate the bridge operation for some token from msg.sender. * The user should first call Approve method of the ERC721 token. * @param token bridged token contract address. * @param _receiver address that will receive the token on the other network. * @param _tokenId id of the token to be transferred to the other network. */ function relayToken( IERC721 token, address _receiver, uint256 _tokenId ) external { _relayToken(token, _receiver, _tokenId); } /** * @dev Initiate the bridge operation for some token from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC721 token. * @param token bridged token contract address. * @param _tokenId id of token to be transferred to the other network. */ function relayToken(IERC721 token, uint256 _tokenId) external { _relayToken(token, msg.sender, _tokenId); } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the token to the contract * and invokes the method to burn/lock the token and unlock/mint the token on the other network. * The user should first call Approve method of the ERC721 token. * @param _token bridge token contract address. * @param _receiver address that will receive the token on the other network. * @param _tokenId id of the token to be transferred to the other network. */ function _relayToken( IERC721 _token, address _receiver, uint256 _tokenId ) internal { // This lock is to prevent calling bridgeSpecificActionsOnTokenTransfer twice. // When transferFrom is called, after the transfer, the ERC721 token might call onERC721Received from this contract // which will call bridgeSpecificActionsOnTokenTransfer. require(!lock()); setLock(true); _token.transferFrom(msg.sender, address(this), _tokenId); setLock(false); bridgeSpecificActionsOnTokenTransfer(address(_token), msg.sender, _receiver, _tokenId); } /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of the token sender. * @param _data passed data in the transfer message. * @return recipient address of the receiver on the other side. */ function chooseReceiver(address _from, bytes memory _data) internal pure returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); } } function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _tokenId ) internal virtual; } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.7.5; interface VersionableBridge { function getBridgeInterfacesVersion() external pure returns ( uint64 major, uint64 minor, uint64 patch ); function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/common/NFTOmnibridgeInfo.sol pragma solidity 0.7.5; /** * @title NFTOmnibridgeInfo * @dev Functionality for versioning NFTOmnibridge mediator. */ contract NFTOmnibridgeInfo is VersionableBridge { event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 tokenId, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 tokenId, bytes32 indexed messageId); /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure override returns ( uint64 major, uint64 minor, uint64 patch ) { return (1, 0, 0); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure override returns (bytes4 _data) { return 0xca7fc3dc; // bytes4(keccak256(abi.encodePacked("multi-nft-to-nft-amb"))) } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/native/NativeTokensRegistry.sol pragma solidity 0.7.5; /** * @title NativeTokensRegistry * @dev Functionality for keeping track of registered native tokens. */ contract NativeTokensRegistry is EternalStorage { /** * @dev Checks if a given token is a bridged token that is native to this side of the bridge. * @param _token address of token contract. * @return message id of the send message. */ function isRegisteredAsNativeToken(address _token) public view returns (bool) { return tokenRegistrationMessageId(_token) != bytes32(0); } /** * @dev Returns message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @return message id of the send message. */ function tokenRegistrationMessageId(address _token) public view returns (bytes32) { return bytes32(uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))]); } /** * @dev Updates message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @param _messageId message id of the send message. */ function _setTokenRegistrationMessageId(address _token, bytes32 _messageId) internal { uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))] = uint256(_messageId); } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.7.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol pragma solidity ^0.7.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: contracts/upgradeable_contracts/omnibridge_nft/components/native/ERC721Reader.sol pragma solidity 0.7.5; /** * @title ERC721Reader * @dev Functionality for reading metadata from the ERC721 tokens. */ contract ERC721Reader is Ownable { /** * @dev Sets the custom metadata for the given ERC721 token. * Only owner can call this method. * Useful when original NFT token does not implement neither name() nor symbol() methods. * @param _token address of the token contract. * @param _name custom name for the token contract. * @param _symbol custom symbol for the token contract. */ function setCustomMetadata( address _token, string calldata _name, string calldata _symbol ) external onlyOwner { stringStorage[keccak256(abi.encodePacked("customName", _token))] = _name; stringStorage[keccak256(abi.encodePacked("customSymbol", _token))] = _symbol; } /** * @dev Internal function for reading ERC721 token name. * Use custom predefined name in case name() function is not implemented. * @param _token address of the ERC721 token contract. * @return name for the token. */ function _readName(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.name.selector)); return status ? abi.decode(data, (string)) : stringStorage[keccak256(abi.encodePacked("customName", _token))]; } /** * @dev Internal function for reading ERC721 token symbol. * Use custom predefined symbol in case symbol() function is not implemented. * @param _token address of the ERC721 token contract. * @return symbol for the token. */ function _readSymbol(address _token) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.symbol.selector)); return status ? abi.decode(data, (string)) : stringStorage[keccak256(abi.encodePacked("customSymbol", _token))]; } /** * @dev Internal function for reading ERC721 token URI. * @param _token address of the ERC721 token contract. * @param _tokenId unique identifier for the token. * @return token URI for the particular token, if any. */ function _readTokenURI(address _token, uint256 _tokenId) internal view returns (string memory) { (bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(IERC721Metadata.tokenURI.selector, _tokenId)); return status ? abi.decode(data, (string)) : ""; } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/BridgedTokensRegistry.sol pragma solidity 0.7.5; /** * @title BridgedTokensRegistry * @dev Functionality for keeping track of registered bridged token pairs. */ contract BridgedTokensRegistry is EternalStorage { event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken); /** * @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side. * @param _nativeToken address of the native token contract on the other side. * @return address of the deployed bridged token contract. */ function bridgedTokenAddress(address _nativeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))]; } /** * @dev Retrieves address of the native token contract associated with a specific bridged token contract. * @param _bridgedToken address of the created bridged token contract on this side. * @return address of the native token contract on the other side of the bridge. */ function nativeTokenAddress(address _bridgedToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))]; } /** * @dev Internal function for updating a pair of addresses for the bridged token. * @param _nativeToken address of the native token contract on the other side. * @param _bridgedToken address of the created bridged token contract on this side. */ function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal { addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken; addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken; emit NewTokenRegistered(_nativeToken, _bridgedToken); } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/TokenImageStorage.sol pragma solidity 0.7.5; /** * @title TokenImageStorage * @dev Storage functionality for working with ERC721 image contract. */ contract TokenImageStorage is Ownable { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) /** * @dev Updates address of the used ERC721 token image. * Only owner can call this method. * @param _image address of the new token image. */ function setTokenImage(address _image) external onlyOwner { _setTokenImage(_image); } /** * @dev Tells the address of the used ERC721 token image. * @return address of the used token image. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } /** * @dev Internal function for updating address of the used ERC721 token image. * @param _image address of the new token image. */ function _setTokenImage(address _image) internal { require(Address.isContract(_image)); addressStorage[TOKEN_IMAGE_CONTRACT] = _image; } } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.7.5; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ abstract contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view virtual returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize()) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize())) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize()) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize()) } default { return(ptr, returndatasize()) } } } } // File: contracts/interfaces/IOwnable.sol pragma solidity 0.7.5; interface IOwnable { function owner() external view returns (address); } // File: contracts/upgradeable_contracts/omnibridge_nft/components/bridged/ERC721TokenProxy.sol pragma solidity 0.7.5; /** * @title ERC721TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract ERC721TokenProxy is Proxy { // storage layout is copied from ERC721BridgeToken.sol mapping(bytes4 => bool) private _supportedInterfaces; mapping(address => uint256) private _holderTokens; //EnumerableMap.UintToAddressMap private _tokenOwners; uint256[] private _tokenOwnersEntries; mapping(bytes32 => uint256) private _tokenOwnersIndexes; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; string private name; string private symbol; mapping(uint256 => string) private _tokenURIs; string private _baseURI; address private bridgeContract; /** * @dev Creates an upgradeable token proxy for ERC721BridgeToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _owner address of the owner for this contract. */ constructor( address _tokenImage, string memory _name, string memory _symbol, address _owner ) { assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage) } name = _name; symbol = _symbol; bridgeContract = _owner; // _owner == HomeOmnibridgeNFT/ForeignOmnibridgeNFT mediator } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return impl token image address. */ function implementation() public view override returns (address impl) { assembly { impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } } /** * @dev Updates the implementation contract address. * Only the bridge and bridge owner can call this method. * @param _implementation address of the new implementation. */ function setImplementation(address _implementation) external { require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner()); require(_implementation != address(0)); require(Address.isContract(_implementation)); assembly { // EIP 1967 // bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1) sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _implementation) } } } // File: contracts/upgradeable_contracts/omnibridge_nft/components/native/NFTMediatorBalanceStorage.sol pragma solidity 0.7.5; /** * @title NFTMediatorBalanceStorage * @dev Functionality for storing expected mediator balance for native tokens. */ contract NFTMediatorBalanceStorage is EternalStorage { /** * @dev Tells if mediator owns the given token. More strict than regular token.ownerOf() check, * since does not take into account forced tokens. * @param _token address of token contract. * @param _tokenId id of the new owned token. * @return true, if given token is already accounted in the mediator balance. */ function mediatorOwns(address _token, uint256 _tokenId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("mediatorOwns", _token, _tokenId))]; } /** * @dev Updates ownership information for the particular token. * @param _token address of token contract. * @param _tokenId id of the new owned token. * @param _owns true, if new token is received. false, when token is released. */ function _setMediatorOwns( address _token, uint256 _tokenId, bool _owns ) internal { boolStorage[keccak256(abi.encodePacked("mediatorOwns", _token, _tokenId))] = _owns; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol pragma solidity ^0.7.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/token/ERC721/IERC721Receiver.sol pragma solidity ^0.7.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/introspection/ERC165.sol pragma solidity ^0.7.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/utils/EnumerableSet.sol pragma solidity ^0.7.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/EnumerableMap.sol pragma solidity ^0.7.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.7.0; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev 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_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_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 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 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 returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `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); _holderTokens[to].add(tokenId); _tokenOwners.set(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 = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(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(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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 { } } // File: contracts/tokens/ERC721BridgeToken.sol pragma solidity 0.7.5; /** * @title ERC721BridgeToken * @dev template token contract for bridged ERC721 tokens. */ contract ERC721BridgeToken is ERC721, IBurnableMintableERC721Token { address public bridgeContract; constructor( string memory _name, string memory _symbol, address _bridgeContract ) ERC721(_name, _symbol) { bridgeContract = _bridgeContract; } /** * @dev Throws if sender is not a bridge contract. */ modifier onlyBridge() { require(msg.sender == bridgeContract); _; } /** * @dev Throws if sender is not a bridge contract or bridge contract owner. */ modifier onlyOwner() { require(msg.sender == bridgeContract || msg.sender == IOwnable(bridgeContract).owner()); _; } /** * @dev Mint new ERC721 token. * Only bridge contract is authorized to mint tokens. * @param _to address of the newly created token owner. * @param _tokenId unique identifier of the minted token. */ function mint(address _to, uint256 _tokenId) external override onlyBridge { _safeMint(_to, _tokenId); } /** * @dev Burns some ERC721 token. * Only bridge contract is authorized to burn tokens. * @param _tokenId unique identifier of the burned token. */ function burn(uint256 _tokenId) external override onlyBridge { _burn(_tokenId); } /** * @dev Sets the base URI for all tokens. * Can be called by bridge owner after token contract was instantiated. * @param _baseURI new base URI. */ function setBaseURI(string calldata _baseURI) external onlyOwner { _setBaseURI(_baseURI); } /** * @dev Updates the bridge contract address. * Can be called by bridge owner after token contract was instantiated. * @param _bridgeContract address of the new bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { require(_bridgeContract != address(0)); bridgeContract = _bridgeContract; } /** * @dev Sets the URI for the particular token. * Can be called by bridge owner after token bridging. * @param _tokenId URI for the bridged token metadata. * @param _tokenURI new token URI. */ function setTokenURI(uint256 _tokenId, string calldata _tokenURI) external override onlyOwner { _setTokenURI(_tokenId, _tokenURI); } } // File: contracts/upgradeable_contracts/omnibridge_nft/BasicNFTOmnibridge.sol pragma solidity 0.7.5; /** * @title BasicNFTOmnibridge * @dev Commong functionality for multi-token mediator for ERC721 tokens intended to work on top of AMB bridge. */ abstract contract BasicNFTOmnibridge is Initializable, Upgradeable, BridgeOperationsStorage, BridgedTokensRegistry, NativeTokensRegistry, NFTOmnibridgeInfo, NFTBridgeLimits, ERC721Reader, TokenImageStorage, ERC721Relayer, NFTMediatorBalanceStorage, FailedMessagesProcessor { /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimit daily limit for outgoing transfers * @param _executionDailyLimit daily limit for ingoing bridge operations * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _image address of the ERC721 token image. */ function initialize( address _bridgeContract, address _mediatorContract, uint256 _dailyLimit, uint256 _executionDailyLimit, uint256 _requestGasLimit, address _owner, address _image ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setDailyLimit(address(0), _dailyLimit); _setExecutionDailyLimit(address(0), _executionDailyLimit); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_image); setInitialize(); return isInitialized(); } /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token was already bridged. */ function isTokenRegistered(address _token) public view override returns (bool) { return isRegisteredAsNativeToken(_token) || nativeTokenAddress(_token) != address(0); } /** * @dev Handles the bridged token for the first time, includes deployment of new ERC721TokenProxy contract. * @param _token address of the native ERC721 token on the other side. * @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, if empty, name will be used instead. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for the bridged token instance. */ function deployAndHandleBridgedNFT( address _token, string calldata _name, string calldata _symbol, address _recipient, uint256 _tokenId, string calldata _tokenURI ) external onlyMediator { address bridgedToken = bridgedTokenAddress(_token); if (bridgedToken == address(0)) { string memory name = _name; string memory symbol = _symbol; if (bytes(name).length == 0) { require(bytes(symbol).length > 0); name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } bridgedToken = address(new ERC721TokenProxy(tokenImage(), _transformName(name), symbol, address(this))); _setTokenAddressPair(_token, bridgedToken); _initToken(bridgedToken); } _handleTokens(bridgedToken, false, _recipient, _tokenId); _setTokenURI(bridgedToken, _tokenId, _tokenURI); } /** * @dev Handles the bridged token for the already registered token pair. * Checks that the bridged token is inside the execution limits and invokes the Mint accordingly. * @param _token address of the native ERC721 token on the other side. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for the bridged token instance. */ function handleBridgedNFT( address _token, address _recipient, uint256 _tokenId, string calldata _tokenURI ) external onlyMediator { address token = bridgedTokenAddress(_token); _handleTokens(token, false, _recipient, _tokenId); _setTokenURI(token, _tokenId, _tokenURI); } /** * @dev Handles the bridged token that are native to this chain. * Checks that the bridged token is inside the execution limits and invokes the Unlock accordingly. * @param _token address of the native ERC721 token contract. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function handleNativeNFT( address _token, address _recipient, uint256 _tokenId ) external onlyMediator { require(isRegisteredAsNativeToken(_token)); _handleTokens(_token, true, _recipient, _tokenId); } /** * @dev Allows to pre-set the bridged token contract for not-yet bridged token. * Only the owner can call this method. * @param _nativeToken address of the token contract on the other side that was not yet bridged. * @param _bridgedToken address of the bridged token contract. */ function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner { require(Address.isContract(_bridgedToken)); require(!isTokenRegistered(_bridgedToken)); require(bridgedTokenAddress(_nativeToken) == address(0)); _setTokenAddressPair(_nativeToken, _bridgedToken); _initToken(_bridgedToken); } /** * @dev Allows to send to the other network some ERC721 token that can be forced into the contract * without the invocation of the required methods. (e. g. regular transferFrom without a call to onERC721Received) * @param _token address of the token contract. * @param _receiver the address that will receive the token on the other network. * @param _tokenId unique id of the bridged token. */ function fixMediatorBalance( address _token, address _receiver, uint256 _tokenId ) external onlyIfUpgradeabilityOwner { require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide()); require(isRegisteredAsNativeToken(_token)); require(!mediatorOwns(_token, _tokenId)); require(IERC721(_token).ownerOf(_tokenId) == address(this)); _setMediatorOwns(_token, _tokenId, true); bytes memory data = abi.encodeWithSelector(this.handleBridgedNFT.selector, _token, _receiver, _tokenId); bytes32 _messageId = bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); _recordBridgeOperation(false, _messageId, _token, _receiver, _tokenId); } /** * @dev Executes action on deposit of ERC721 token. * @param _token address of the ERC721 token contract. * @param _from address of token sender. * @param _receiver address of token receiver on the other side. * @param _tokenId unique id of the bridged token. */ function bridgeSpecificActionsOnTokenTransfer( address _token, address _from, address _receiver, uint256 _tokenId ) internal override { require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide()); bool isKnownToken = isTokenRegistered(_token); bool isNativeToken = !isKnownToken || isRegisteredAsNativeToken(_token); bytes memory data; if (!isKnownToken) { require(IERC721(_token).ownerOf(_tokenId) == address(this)); string memory name = _readName(_token); string memory symbol = _readSymbol(_token); string memory tokenURI = _readTokenURI(_token, _tokenId); require(bytes(name).length > 0 || bytes(symbol).length > 0); _initToken(_token); data = abi.encodeWithSelector( this.deployAndHandleBridgedNFT.selector, _token, name, symbol, _receiver, _tokenId, tokenURI ); } else if (isNativeToken) { string memory tokenURI = _readTokenURI(_token, _tokenId); data = abi.encodeWithSelector(this.handleBridgedNFT.selector, _token, _receiver, _tokenId, tokenURI); } else { IBurnableMintableERC721Token(_token).burn(_tokenId); data = abi.encodeWithSelector( this.handleNativeNFT.selector, nativeTokenAddress(_token), _receiver, _tokenId ); } if (isNativeToken) { _setMediatorOwns(_token, _tokenId, true); } bytes32 _messageId = bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); _recordBridgeOperation(!isKnownToken, _messageId, _token, _from, _tokenId); } /** * @dev Unlock/Mint back the bridged token that was bridged to the other network but failed. * @param _messageId id of the failed message. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function executeActionOnFixedTokens( bytes32 _messageId, address _token, address _recipient, uint256 _tokenId ) internal override { bytes32 registrationMessageId = tokenRegistrationMessageId(_token); if (_messageId == registrationMessageId) { delete uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; delete uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; _setTokenRegistrationMessageId(_token, bytes32(0)); } _releaseToken(_token, registrationMessageId != bytes32(0), _recipient, _tokenId); } /** * @dev Handles the bridged token that came from the other side of the bridge. * Checks that the operation is inside the execution limits and invokes the Mint or Unlock accordingly. * @param _token token contract address on this side of the bridge. * @param _isNative true, if given token is native to this chain and Unlock should be used. * @param _recipient address that will receive the tokens. * @param _tokenId unique id of the bridged token. */ function _handleTokens( address _token, bool _isNative, address _recipient, uint256 _tokenId ) internal { require(withinExecutionLimit(_token)); addTotalExecutedPerDay(_token); _releaseToken(_token, _isNative, _recipient, _tokenId); emit TokensBridged(_token, _recipient, _tokenId, messageId()); } /** * Internal function for setting token URI for the bridged token instance. * @param _token address of the token contract. * @param _tokenId unique id of the bridged token. * @param _tokenURI URI for bridged token metadata. */ function _setTokenURI( address _token, uint256 _tokenId, string calldata _tokenURI ) internal { if (bytes(_tokenURI).length > 0) { IBurnableMintableERC721Token(_token).setTokenURI(_tokenId, _tokenURI); } } /** * Internal function for unlocking/minting some specific ERC721 token. * @param _token address of the token contract. * @param _isNative true, if the token contract is native w.r.t to the bridge. * @param _recipient address of the tokens receiver. * @param _tokenId unique id of the bridged token. */ function _releaseToken( address _token, bool _isNative, address _recipient, uint256 _tokenId ) internal { if (_isNative) { _setMediatorOwns(_token, _tokenId, false); IERC721(_token).transferFrom(address(this), _recipient, _tokenId); } else { IBurnableMintableERC721Token(_token).mint(_recipient, _tokenId); } } /** * @dev Internal function for recording bridge operation for further usage. * Recorded information is used for fixing failed requests on the other side. * @param _register true, if native token is bridged for the first time. * @param _messageId id of the sent message. * @param _token bridged token address. * @param _sender address of the tokens sender. * @param _tokenId unique id of the bridged token. */ function _recordBridgeOperation( bool _register, bytes32 _messageId, address _token, address _sender, uint256 _tokenId ) internal { require(withinLimit(_token)); addTotalSpentPerDay(_token); setMessageToken(_messageId, _token); setMessageRecipient(_messageId, _sender); setMessageValue(_messageId, _tokenId); if (_register) { _setTokenRegistrationMessageId(_token, _messageId); } emit TokensBridgingInitiated(_token, _sender, _tokenId, _messageId); } /** * @dev Internal function for initializing newly bridged token related information. * @param _token address of the token contract. */ function _initToken(address _token) internal { _setDailyLimit(_token, dailyLimit(address(0))); _setExecutionDailyLimit(_token, executionDailyLimit(address(0))); } function _transformName(string memory _name) internal pure virtual returns (string memory); } // File: contracts/upgradeable_contracts/omnibridge_nft/ForeignNFTOmnibridge.sol pragma solidity 0.7.5; /** * @title ForeignNFTOmnibridge * @dev Foreign side implementation for multi-token ERC721 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignNFTOmnibridge is BasicNFTOmnibridge { /** * @dev Internal function for transforming the bridged token name. Appends a side-specific suffix. * @param _name bridged token from the other side. * @return token name for this side of the bridge. */ function _transformName(string memory _name) internal pure override returns (string memory) { return string(abi.encodePacked(_name, " on Mainnet")); } }
Handles the bridged token that are native to this chain. Checks that the bridged token is inside the execution limits and invokes the Unlock accordingly. _token address of the native ERC721 token contract. _recipient address that will receive the tokens. _tokenId unique id of the bridged token./
function handleNativeNFT( address _token, address _recipient, uint256 _tokenId ) external onlyMediator { require(isRegisteredAsNativeToken(_token)); _handleTokens(_token, true, _recipient, _tokenId); }
14,530,546
//Address: 0xc8af1ed873a5c2aafce10fe4e67124876c50e239 //Contract name: P2PFuturesTrading //Balance: 0 Ether //Verification Date: 6/23/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.11; /* P2PFuturesTrading Trustless trading of not already transferable tokens between two people Author: thestral.eth */ // ERC20 Interface: ethereum/EIPs#20 contract ERC20 { function transferFrom(address _from, address _to, uint256 _value) returns (bool success); } contract P2PFuturesTrading { struct Trade{ address tokenAddress; uint tokenAmount; uint etherAmount; uint etherCollateralAmount; uint endTradeBlock; bool initialized; bool finalized; } // Store the open trades mapping (address => mapping(address => Trade)) public trades; // The developer address. address developerAddress = 0x335854eF79Fff47F9050ca853c7f3bA53eeEEE93; function startTrade(address tokenSellerAddress, address tokenAddress, uint tokenAmount, uint etherCollateralAmount, uint endTradeBlock) payable{ //Variable validation. The endTradeBlock can't be smaller than the current one plus 220 (around 1 hour) if(msg.value == 0 || tokenAmount == 0 || endTradeBlock <= block.number + 220){ throw; } Trade t1 = trades[msg.sender][tokenSellerAddress]; Trade t2 = trades[tokenSellerAddress][msg.sender]; //You can't have more than one trade at a time between the same two people. To close a non finalized trade and have you ether back, you need to call the function cancelTrade if(t1.initialized || t2.initialized){ throw; } trades[msg.sender][tokenSellerAddress] = Trade(tokenAddress, tokenAmount, msg.value, etherCollateralAmount, endTradeBlock, true, false); } function finalizeTrade(address tokenBuyerAddress, uint etherAmount, address tokenAddress, uint tokenAmount, uint endTradeBlock) payable{ Trade t = trades[tokenBuyerAddress][msg.sender]; //It needs to exist already a trade between the two people and it hasn't have to be already finalized if(!t.initialized || t.finalized){ throw; } //The trade condition specified by the two people must concide if(!(t.tokenAddress == tokenAddress && t.tokenAmount == tokenAmount && t.etherAmount == etherAmount && t.etherCollateralAmount == msg.value && t.endTradeBlock == endTradeBlock)){ throw; } t.finalized = true; } function completeTrade(address otherPersonAddress){ Trade t; address tokenBuyerAddress; address tokenSellerAddress; Trade tokenBuyerTrade = trades[msg.sender][otherPersonAddress]; Trade tokenSellerTrade = trades[otherPersonAddress][msg.sender]; //It needs to exist already a trade between the two people and it has to be already finalized. if(tokenBuyerTrade.initialized && tokenBuyerTrade.finalized){ t = tokenBuyerTrade; tokenBuyerAddress = msg.sender; tokenSellerAddress = otherPersonAddress; } else if(tokenSellerTrade.initialized && tokenSellerTrade.finalized){ t = tokenSellerTrade; tokenBuyerAddress = otherPersonAddress; tokenSellerAddress = msg.sender; } else{ throw; } ERC20 token = ERC20(t.tokenAddress); //1% developer fee, 0.5% from the tokenSeller (in tokens) and 0.5% from the tokenBuyer (in ethers). In case the trade doesn't complete the fee is of 1% of the collateral. uint tokenSellerFee = t.tokenAmount * 5 / 1000; uint tokenBuyerFee = t.etherAmount * 5 / 1000; uint collateralFee = t.etherCollateralAmount / 100; t.initialized = false; t.finalized = false; //If the tokenSeller didn't allow this contract of the needed amount, one of the two following functions will return false if(!token.transferFrom(tokenSellerAddress, tokenBuyerAddress, t.tokenAmount - tokenSellerFee) || !token.transferFrom(tokenSellerAddress, developerAddress, tokenSellerFee)){ //If the maximum time has passed, and the trade coudldn't be completed, the tokenBuyer will receive his ether plus the collateral. Otherwise no action is taken. if(t.endTradeBlock < block.number){ tokenBuyerAddress.transfer(t.etherAmount + t.etherCollateralAmount - collateralFee); developerAddress.transfer(collateralFee); return; } else{ throw; } } //Transfer to the tokenSeller the etherAmount plus his collateral tokenSellerAddress.transfer(t.etherAmount + t.etherCollateralAmount - tokenBuyerFee); developerAddress.transfer(tokenBuyerFee); } function cancelTrade(address tokenSellerAddress){ Trade t = trades[msg.sender][tokenSellerAddress]; //It needs to exist already a trade between the two people and it hasn't have to be already finalized if(!t.initialized || t.finalized){ throw; } //Cancel the trade and give the sender his ether back t.initialized = false; msg.sender.transfer(t.etherAmount); } }
It needs to exist already a trade between the two people and it hasn't have to be already finalized
function cancelTrade(address tokenSellerAddress){ Trade t = trades[msg.sender][tokenSellerAddress]; if(!t.initialized || t.finalized){ throw; } msg.sender.transfer(t.etherAmount); }
5,418,221
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.11; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; /* NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNmmmmmNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNmmddmNNNmddmmNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNmhhdNNNNmdddmNNNNmhhmNNNNNNNNNNNNNNN NNNNNNNNNNmhs+///+syhdmNNNmmhyo/:::/shmNNNNNNNNNNN NNNNNNNNNNy:::::/:://+shdho/:-------..oNNNNNNNNNNN NNNNNNNNNNs::::::::::::::.............+NNNNNNNNNNN NNNNNNNNNNs:::::::::::::-.....--......+NNNNNNNNNNN NNNNNNNNNNs:::::://:///:--------......+NNNNNNNNNNN NNNNNNNNNNs::::+///:////:::------:....+NNNNNNNNNNN NNNNNNNNNNs::::mdyo/////:::-::+ydm:...+NNNNNNNNNNN NNNNNNNNNNs::::NNNNhdyo+:/+ydhNNNN:...+NNNNNNNNNNN NNNNNNNNNNs::::mNNNdNNNmymNNNdNNNm:...+NNNNNNNNNNN NNNNNNNNNNs:::/mmmmhNNNNdNNNNhmmmm:...+NNNNNNNNNNN NNNNNNNNNNd+//:NNNNhmmmmdNmmmhNNNN:.-/yNNNNNNNNNNN NNNNNNNNNNNNmdymmNNdNNNNhmNNNdNNNmyhmNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNmmhmNNNdNNNNhmmmNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNmmmhmmmmNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN */ /// @title ERC-721 token for Meta Mint Alpha Pass. /// @author @ItsCuzzo contract AlphaPass is Ownable, ERC721 { using Strings for uint; using Counters for Counters.Counter; string private _tokenURI; string private _contractURI; Counters.Counter private _tokenIdCounter; uint public maxSupply = 300; uint public tokenPrice = 0.4 ether; uint public renewalPrice = 0.1 ether; uint public maxTokensPerTx = 3; uint public gracePeriod = 3 days; mapping(uint => uint) public expiryTime; mapping(uint => bool) public isBanned; struct DutchAuction { uint32 startTime; uint72 startingPrice; uint16 stepDuration; uint72 reservePrice; uint64 decrementAmount; } enum SaleStates { PAUSED, FCFS_MINT, DUTCH_AUCTION } DutchAuction public auction; SaleStates public saleState; event Minted(address indexed _from, uint _amount); event Renewed(address indexed _from, uint _tokenId); event RenewedBatch(address indexed _from, uint[] _tokenIds); event Banned(address indexed _from, uint _tokenId); event Unbanned(address indexed _from, uint _tokenId); constructor( string memory tokenURI_, string memory contractURI_ ) ERC721("Alpha Pass", "ALPHA") { _tokenURI = tokenURI_; _contractURI = contractURI_; } /// @notice Function used to mint a token during the `DUTCH_AUCTION` sale. function auctionMint() external payable { require(tx.origin == msg.sender, "Caller should not be a contract."); require(SaleStates.DUTCH_AUCTION == saleState, "Auction not active."); require(auction.startTime <= block.timestamp, "Auction has not started."); uint tokenIndex = _tokenIdCounter.current() + 1; require(maxSupply >= tokenIndex, "Minted tokens would exceed supply."); require(msg.value >= getAuctionPrice(), "Incorrect Ether amount."); _tokenIdCounter.increment(); _safeMint(msg.sender, tokenIndex); expiryTime[tokenIndex] = block.timestamp + 30 days; emit Minted(msg.sender, 1); } /// @notice Function used to mint tokens during the `FCFS_MINT` sale. /// @param numTokens The desired number of tokens to mint. function mint(uint numTokens) external payable { require(tx.origin == msg.sender, "Caller should not be a contract."); require(saleState == SaleStates.FCFS_MINT, "FCFS minting is not active."); require(tokenPrice * numTokens == msg.value, "Incorrect Ether amount."); require(maxSupply >= _tokenIdCounter.current() + numTokens, "Minted tokens would exceed supply."); require(maxTokensPerTx >= numTokens, "Token tx limit exceeded."); for (uint i=0; i<numTokens; i++) { _tokenIdCounter.increment(); uint tokenIndex = _tokenIdCounter.current(); _safeMint(msg.sender, tokenIndex); expiryTime[tokenIndex] = block.timestamp + 30 days; } emit Minted(msg.sender, numTokens); } /// @notice Function that is used to extend/renew a tokens expiry date /// in increments of 30 days. /// @param tokenId The token ID to extend/renew. function renewToken(uint tokenId) public payable { require(_exists(tokenId), "Token does not exist."); require(ownerOf(tokenId) == msg.sender, "Caller does not own token."); require(!isBanned[tokenId], "Token is banned."); require(msg.value == renewalPrice, "Incorrect Ether amount."); uint _currentexpiryTime = expiryTime[tokenId]; if (block.timestamp > _currentexpiryTime) { expiryTime[tokenId] = block.timestamp + 30 days; } else { expiryTime[tokenId] += 30 days; } emit Renewed(msg.sender, tokenId); } /// @notice Function that is used to extend/renew multiple tokens expiry date /// in increments of 30 days. /// @param tokenIds The token IDs to extend/renew. function batchRenewToken(uint[] calldata tokenIds) public payable { require(tokenIds.length >= 2, "Invalid array length."); require(renewalPrice * tokenIds.length == msg.value, "Incorrect Ether amount."); for (uint i=0; i<tokenIds.length; i++) { require(_exists(tokenIds[i]), "Token does not exist."); require(ownerOf(tokenIds[i]) == msg.sender, "Caller does not own token."); require(!isBanned[tokenIds[i]], "Token is banned."); uint _currentexpiryTime = expiryTime[tokenIds[i]]; if (block.timestamp > _currentexpiryTime) { expiryTime[tokenIds[i]] = block.timestamp + 30 days; } else { expiryTime[tokenIds[i]] += 30 days; } } emit RenewedBatch(msg.sender, tokenIds); } /// @notice Function that is used to mint a token free of charge, only /// callable by the owner. function ownerMint(address receiver) public onlyOwner { uint tokenIndex = _tokenIdCounter.current() + 1; require(maxSupply >= tokenIndex, "Minted tokens would exceed supply."); _tokenIdCounter.increment(); _safeMint(receiver, tokenIndex); expiryTime[tokenIndex] = block.timestamp + 30 days; emit Minted(msg.sender, 1); } /// @notice Function that is used to extend/renew a tokens expiry date /// in increments of 30 days free of charge, only callable by the owner. /// @param tokenId The token ID to extend/renew. function ownerRenewToken(uint tokenId) public onlyOwner { require(_exists(tokenId), "Token does not exist."); uint _currentexpiryTime = expiryTime[tokenId]; if (block.timestamp > _currentexpiryTime) { expiryTime[tokenId] = block.timestamp + 30 days; } else { expiryTime[tokenId] += 30 days; } emit Renewed(msg.sender, tokenId); } /// @notice Function that is used to extend/renew multiple tokens expiry date /// in increments of 30 days free of charge, only callable by the owner. /// @param tokenIds The token IDs to extend/renew. function ownerBatchRenewToken(uint[] calldata tokenIds) public onlyOwner { require(tokenIds.length >= 2, "Invalid array length."); for (uint i=0; i<tokenIds.length; i++) { require(_exists(tokenIds[i]), "Token does not exist."); uint _currentexpiryTime = expiryTime[tokenIds[i]]; if (block.timestamp > _currentexpiryTime) { expiryTime[tokenIds[i]] = block.timestamp + 30 days; } else { expiryTime[tokenIds[i]] += 30 days; } } emit RenewedBatch(msg.sender, tokenIds); } /// @notice Function used to get the current price of a token during the /// dutch auction. /// @dev This function should be polled externally to determine how much /// Ether a participant should send. /// @return Returns a uint indicating the current price of the token in /// wei. function getAuctionPrice() public view returns (uint72) { if (saleState != SaleStates.DUTCH_AUCTION || auction.startTime >= block.timestamp) { return auction.startingPrice; } uint72 decrements = (uint72(block.timestamp) - auction.startTime) / auction.stepDuration; if (decrements * auction.decrementAmount >= auction.startingPrice) { return auction.reservePrice; } if (auction.startingPrice - decrements * auction.decrementAmount < auction.reservePrice) { return auction.reservePrice; } return auction.startingPrice - decrements * auction.decrementAmount; } /// @notice Function used to define the dutch auction settings. /// @param _startTime Starting time for the auction in seconds. /// @param _startingPrice Starting price for the auction in wei. /// @param _stepDuration Time between each price decrease, in seconds. /// @param _reservePrice Reserve price for the auction in wei. /// @param _decrementAmount Amount that price decreases every step, in wei. /// @dev Reasoning for doing one function for all updates is that once the /// auction is configured once, it shouldn't need changing until afterwards. function setAuctionBulk( uint32 _startTime, uint72 _startingPrice, uint16 _stepDuration, uint72 _reservePrice, uint64 _decrementAmount ) external onlyOwner { require(_startTime > block.timestamp, "Invalid start time."); require(_startingPrice > _reservePrice, "Initial price must exceed reserve."); auction.startTime = _startTime; auction.startingPrice = _startingPrice; auction.stepDuration = _stepDuration; auction.reservePrice = _reservePrice; auction.decrementAmount = _decrementAmount; } /// @notice Function used to set the dutch auction start time. /// @param _startTime A UNIX epoch, in seconds, of the intended start time. /// @dev Pssst, https://www.epochconverter.com/ function setAuctionStartTime(uint32 _startTime) external onlyOwner { require(_startTime > block.timestamp, "Invalid start time."); auction.startTime = _startTime; } /// @notice Function used to set the starting price of the dutch auction. /// @param _startingPrice uint value in wei representing the starting price. function setAuctionStartingPrice(uint72 _startingPrice) external onlyOwner { require(auction.startingPrice != _startingPrice, "Price has not changed."); auction.startingPrice = _startingPrice; } /// @notice Function used to set the step time during the dutch auction. /// @param _stepDuration uint value is seconds representing how frequently the /// price will drop. E.g. Input of 120 is equivalent to 2 minutes. function setAuctionStepDuration(uint16 _stepDuration) external onlyOwner { require(auction.stepDuration != _stepDuration, "Duration has not changed."); auction.stepDuration = _stepDuration; } /// @notice Function used to set the dutch auction reserve price. /// @param _reservePrice Represents the reserve price in units of wei. function setAuctionReservePrice(uint72 _reservePrice) external onlyOwner { require(auction.reservePrice != _reservePrice, "Price has not changed."); auction.reservePrice = _reservePrice; } /// @notice Function used to set the dutch auction decrement amount. /// @param _decrementAmount uint value representing how much the price /// will drop each step. E.g. 25000000000000000 is 0.025 Ether. function setAuctionDecrementAmount(uint64 _decrementAmount) external onlyOwner { require(auction.decrementAmount != _decrementAmount, "Decrement has not changed."); auction.decrementAmount = _decrementAmount; } /// @notice Function that is used to update the `renewalPrice` variable, /// only callable by the owner. /// @param newRenewalPrice The new renewal price in units of wei. E.g. /// 500000000000000000 is 0.50 Ether. function updateRenewalPrice(uint newRenewalPrice) external onlyOwner { require(renewalPrice != newRenewalPrice, "Price has not changed."); renewalPrice = newRenewalPrice; } /// @notice Function that is used to update the `tokenPrice` variable, /// only callable by the owner. /// @param newTokenPrice The new initial token price in units of wei. E.g. /// 2000000000000000000 is 2 Ether. function updateTokenPrice(uint newTokenPrice) external onlyOwner { require(tokenPrice != newTokenPrice, "Price has not changed."); tokenPrice = newTokenPrice; } /// @notice Function that is used to update the `maxTokensPerTx` variable, /// only callable by the owner. /// @param newMaxTokensPerTx The new maximum amount of tokens a user can /// mint in a single tx. function updateMaxTokensPerTx(uint newMaxTokensPerTx) external onlyOwner { require(maxTokensPerTx != newMaxTokensPerTx, "Max tokens has not changed."); maxTokensPerTx = newMaxTokensPerTx; } /// @notice Function that is used to update the `GRACE_PERIOD` variable, /// only callable by the owner. /// @param newGracePeriod The new grace period in units of seconds in wei. /// E.g. 2592000 is 30 days. /// @dev Grace period should be atleast 1 day, uint value of 86400. function updateGracePeriod(uint newGracePeriod) external onlyOwner { require(gracePeriod != newGracePeriod, "Duration has not changed."); require(newGracePeriod % 1 days == 0, "Must provide 1 day increments."); gracePeriod = newGracePeriod; } /// @notice Function used to set a new `saleState` value. /// @param newSaleState The newly desired sale state. /// @dev 0 = PAUSED, 1 = FCFS_MINT, 2 = DUTCH_AUCTION. function setSaleState(uint newSaleState) external onlyOwner { require(uint(SaleStates.DUTCH_AUCTION) >= newSaleState, "Invalid sale state."); saleState = SaleStates(newSaleState); } /// @notice Function that is used to authenticate a user. /// @param tokenId The desired token owned by a user. /// @return Returns a bool value determining if authentication was /// was successful. `true` is successful, `false` if otherwise. function authenticateUser(uint tokenId) public view returns (bool) { require(_exists(tokenId), "Token does not exist."); require(!isBanned[tokenId], "Token is banned."); require(expiryTime[tokenId] + gracePeriod > block.timestamp, "Token has expired. Please renew!"); return msg.sender == ownerOf(tokenId) ? true : false; } /// @notice Function used to increment the `maxSupply` value. /// @param numTokens The amount of tokens to add to `maxSupply`. function addTokens(uint numTokens) external onlyOwner { maxSupply += numTokens; } /// @notice Function used to decrement the `maxSupply` value. /// @param numTokens The amount of tokens to remove from `maxSupply`. function removeTokens(uint numTokens) external onlyOwner { require(maxSupply - numTokens >= _tokenIdCounter.current(), "Supply cannot fall below minted tokens."); maxSupply -= numTokens; } /// @notice Function used to ban a token, only callable by the owner. /// @param tokenId The token ID to ban. function banToken(uint tokenId) external onlyOwner { require(!isBanned[tokenId], "Token already banned."); expiryTime[tokenId] = block.timestamp; isBanned[tokenId] = true; emit Banned(msg.sender, tokenId); } /// @notice Function used to unban a token, only callable by the owner. /// @param tokenId The token ID to unban. function unbanToken(uint tokenId) external onlyOwner { require(isBanned[tokenId], "Token is not banned."); isBanned[tokenId] = false; emit Unbanned(msg.sender, tokenId); } /// @notice Function that is used to get the current `_contractURI` value. /// @return Returns a string value of `_contractURI`. function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Function that is used to update the `_contractURI` value, only /// callable by the owner. /// @param contractURI_ A string value to replace the current 'contractURI_'. function setContractURI(string calldata contractURI_) external onlyOwner { _contractURI = contractURI_; } /// @notice Function that is used to get the `_tokenURI` for `tokenId`. /// @param tokenId The `tokenId` to get the `_tokenURI` for. /// @return Returns a string representing the `_tokenURI` for `tokenId`. function tokenURI(uint tokenId) public view override returns (string memory) { require(_exists(tokenId), "Token does not exist."); return string(abi.encodePacked(_tokenURI, tokenId.toString())); } /// @notice Function that is used to update the `_tokenURI` value, only /// callable by the owner. /// @param tokenURI_ A string value to replace the current `_tokenURI` value. function setTokenURI(string calldata tokenURI_) external onlyOwner { _tokenURI = tokenURI_; } /// @notice Function used to get the total number of minted tokens. function totalSupply() public view returns (uint) { return _tokenIdCounter.current(); } /// @notice Function that is used to withdraw the total balance of the /// contract, only callable by the owner. function withdrawBalance() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @notice Function used to get the tokens owned by a provided address. /// @param _address The specified address to perform a lookup for. /// @dev DO NOT CALL THIS FUNCTION ON-CHAIN. function getTokensOwnedByAddress(address _address) external view returns (uint[] memory) { uint tokenBalance = balanceOf(_address); if (tokenBalance == 0) { return new uint[](0); } uint[] memory tokensOwned = new uint[](tokenBalance); uint resultIndex = 0; for (uint i=1; i<=_tokenIdCounter.current(); i++) { if (ownerOf(i) == _address) { tokensOwned[resultIndex] = i; resultIndex++; } } return tokensOwned; } /// @notice Function used to get the tokens currently within the grace period. /// @dev DO NOT CALL THIS FUNCTION ON-CHAIN. function getTokensInGracePeriod() external view returns (uint[] memory) { uint tokenSupply = _tokenIdCounter.current(); uint numTokens = 0; for (uint i=1; i<=tokenSupply; i++) { if (block.timestamp > expiryTime[i] && expiryTime[i] + gracePeriod > block.timestamp) { if (!isBanned[i]) { numTokens++; } } } uint[] memory graceTokens = new uint[](numTokens); uint index = 0; for (uint i=1; i<=tokenSupply; i++) { if (block.timestamp > expiryTime[i] && expiryTime[i] + gracePeriod > block.timestamp) { if (!isBanned[i]) { graceTokens[index] = i; index++; } } } return graceTokens; } /// @notice Function that is used to safely transfer a token from one owner to another. function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "Transfer caller is not owner nor approved."); if (owner() != msg.sender) { require(!isBanned[tokenId], "Token is banned."); require(expiryTime[tokenId] > block.timestamp, "Token has expired."); } _safeTransfer(from, to, tokenId, _data); } /// @notice Function that is used to transfer a token from one owner to another. function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "Transfer caller is not owner nor approved."); if (owner() != msg.sender) { require(!isBanned[tokenId], "Token is banned."); require(expiryTime[tokenId] > block.timestamp, "Token has expired."); } _transfer(from, to, tokenId); } } // 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/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // 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 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); }
Function used to define the dutch auction settings. _startTime Starting time for the auction in seconds. _startingPrice Starting price for the auction in wei. _stepDuration Time between each price decrease, in seconds. _reservePrice Reserve price for the auction in wei. _decrementAmount Amount that price decreases every step, in wei. Reasoning for doing one function for all updates is that once the auction is configured once, it shouldn't need changing until afterwards.
function setAuctionBulk( uint32 _startTime, uint72 _startingPrice, uint16 _stepDuration, uint72 _reservePrice, uint64 _decrementAmount ) external onlyOwner { require(_startTime > block.timestamp, "Invalid start time."); require(_startingPrice > _reservePrice, "Initial price must exceed reserve."); auction.startTime = _startTime; auction.startingPrice = _startingPrice; auction.stepDuration = _stepDuration; auction.reservePrice = _reservePrice; auction.decrementAmount = _decrementAmount; }
478,195
./partial_match/1/0xF4Ec558DA9C9441bFAAD01645dFf0df2Eb20ccd6/sources/SailBot.sol
Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; }
11,017,481
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // Will be replaced by DFY-AccessControl when it's merged or later phases. import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./IReputation.sol"; contract Reputation is IReputation, UUPSUpgradeable, PausableUpgradeable, AccessControlUpgradeable { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using AddressUpgradeable for address; /** * @dev PAUSER_ROLE: those who can pause the contract * by default this role is assigned _to the contract creator. */ bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // mapping of user address's reputation score mapping (address => uint32) private _reputationScore; mapping(ReasonType => int8) _rewardByReason; mapping(address => bool) whitelistedContractCaller; event ReputationPointRewarded(address _user, uint256 _points, ReasonType _reasonType); event ReputationPointReduced(address _user, uint256 _points, ReasonType _reasonType); function initialize() public initializer { __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); //initialize Reward by Reason mapping values. _initializeRewardByReason(); } // Reason for Reputation point adjustment /** * @dev Reputation points in correspondence with ReasonType * LD_CREATE_PACKAGE : +3 (0) * LD_CANCEL_PACKAGE : -3 (1) * LD_REOPEN_PACKAGE : +3 (2) * LD_GENERATE_CONTRACT : +1 (3) * LD_CREATE_OFFER : +2 (4) * LD_CANCEL_OFFER : -2 (5) * LD_ACCEPT_OFFER : +1 (6) * BR_CREATE_COLLATERAL : +3 (7) * BR_CANCEL_COLLATERAL : -3 (8) * BR_ONTIME_PAYMENT : +1 (9) * BR_LATE_PAYMENT : -1 (10) * BR_ACCEPT_OFFER : +1 (11) * BR_CONTRACT_COMPLETE : +5 (12) * BR_CONTRACT_DEFAULTED : -5 (13) * LD_REVIEWED_BY_BORROWER_1 : +1 (14) * LD_REVIEWED_BY_BORROWER_2 : +2 (15) * LD_REVIEWED_BY_BORROWER_3 : +3 (16) * LD_REVIEWED_BY_BORROWER_4 : +4 (17) * LD_REVIEWED_BY_BORROWER_5 : +5 (18) * LD_KYC : +5 (19) * BR_REVIEWED_BY_LENDER_1 : +1 (20) * BR_REVIEWED_BY_LENDER_2 : +2 (21) * BR_REVIEWED_BY_LENDER_3 : +3 (22) * BR_REVIEWED_BY_LENDER_4 : +4 (23) * BR_REVIEWED_BY_LENDER_5 : +5 (24) * BR_KYC : +5 (25) */ function _initializeRewardByReason() internal virtual { _rewardByReason[ReasonType.LD_CREATE_PACKAGE] = 3; // index: 0 _rewardByReason[ReasonType.LD_CANCEL_PACKAGE] = -3; // index: 1 _rewardByReason[ReasonType.LD_REOPEN_PACKAGE] = 3; // index: 2 _rewardByReason[ReasonType.LD_GENERATE_CONTRACT] = 1; // index: 3 _rewardByReason[ReasonType.LD_CREATE_OFFER] = 2; // index: 4 _rewardByReason[ReasonType.LD_CANCEL_OFFER] = -2; // index: 5 _rewardByReason[ReasonType.LD_ACCEPT_OFFER] = 1; // index: 6 _rewardByReason[ReasonType.BR_CREATE_COLLATERAL] = 3; // index: 7 _rewardByReason[ReasonType.BR_CANCEL_COLLATERAL] = -3; // index: 8 _rewardByReason[ReasonType.BR_ONTIME_PAYMENT] = 1; // index: 9 _rewardByReason[ReasonType.BR_LATE_PAYMENT] = -1; // index: 10 _rewardByReason[ReasonType.BR_ACCEPT_OFFER] = 1; // index: 11 _rewardByReason[ReasonType.BR_CONTRACT_COMPLETE] = 5; // index: 12 _rewardByReason[ReasonType.BR_CONTRACT_DEFAULTED]= -5; // index: 13 } function initializeRewardByReason() external onlyRole(DEFAULT_ADMIN_ROLE) { _initializeRewardByReason(); } function _authorizeUpgrade(address) internal override onlyRole(DEFAULT_ADMIN_ROLE) {} function version() public virtual pure returns (string memory) { return "1.0.2"; } modifier isNotZeroAddress(address _to) { require(_to != address(0), "DFY: Reward pawn reputation to the zero address"); _; } modifier onlyEOA(address _to) { require(!_to.isContract(), "DFY: Reward pawn reputation to a contract address"); _; } modifier onlyWhitelistedContractCaller(address _from) { // Caller must be a contract require(_from.isContract(), "DFY: Calling Reputation adjustment from a non-contract address"); // Caller must be whitelisted require(whitelistedContractCaller[_from] == true, "DFY: Caller is not allowed"); _; } /** * @dev Add a contract address that use Reputation to whitelist * @param _caller is the contract address being whitelisted= */ function addWhitelistedContractCaller(address _caller) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_caller.isContract(), "DFY: Setting reputation contract caller to a non-contract address"); whitelistedContractCaller[_caller] = true; } /** * @dev remove a contract address from whitelist * @param _caller is the contract address being removed */ function removeWhitelistedContractCaller(address _caller) external onlyRole(DEFAULT_ADMIN_ROLE) { delete whitelistedContractCaller[_caller]; } /** * @dev check if an address is whitelisted * @param _contract is the address being verified */ function isWhitelistedContractCaller(address _contract) external view returns (bool) { return whitelistedContractCaller[_contract]; } /** * @dev Get the reputation score of an account */ function getReputationScore(address _address) external virtual override view returns(uint32) { return _reputationScore[_address]; } /** * @dev Return the absolute value of a signed integer * @param _input is any signed integer * @return an unsigned integer that is the absolute value of _input */ function abs(int256 _input) internal pure returns (uint256) { return _input >= 0 ? uint256(_input) : uint256(_input * -1); } /** * @dev Adjust reputation score base on the input reason * @param _user is the address of the user whose reputation score is being adjusted. * @param _reasonType is the reason of the adjustment. */ function adjustReputationScore( address _user, ReasonType _reasonType) external override whenNotPaused isNotZeroAddress(_user) onlyEOA(_user) onlyWhitelistedContractCaller(_msgSender()) { int8 pointsByReason = _rewardByReason[_reasonType]; uint256 points = abs(pointsByReason); // Check if the points mapped by _reasonType is greater than 0 or not if(pointsByReason >= 0) { // If pointsByReason is greater than 0, reward points to the user. _rewardReputationScore(_user, points, _reasonType); } else { // If pointByReason is lesser than 0, substract the points from user's current score. _reduceReputationScore(_user, points, _reasonType); } } /** * @dev Reward Reputation score to a user * @param _to is the address whose reputation score is going to be adjusted * @param _points is the points will be added to _to's reputation score (unsigned integer) * @param _reasonType is the reason of score adjustment */ function _rewardReputationScore( address _to, uint256 _points, ReasonType _reasonType) internal { uint256 currentScore = uint256(_reputationScore[_to]); _reputationScore[_to] = currentScore.add(_points).toUint32(); emit ReputationPointRewarded(_to, _points, _reasonType); } /** * @dev Reduce Reputation score of a user. * @param _from is the address whose reputation score is going to be adjusted * @param _points is the points will be subtracted from _from's reputation score (unsigned integer) * @param _reasonType is the reason of score adjustment */ function _reduceReputationScore( address _from, uint256 _points, ReasonType _reasonType) internal { uint256 currentScore = uint256(_reputationScore[_from]); (bool success, uint result) = currentScore.trySub(_points); // if the current reputation score is lesser than the reducing points, // set reputation score to 0 _reputationScore[_from] = success == true ? result.toUint32() : 0; emit ReputationPointReduced(_from, _points, _reasonType); } }
initialize Reward by Reason mapping values.
function initialize() public initializer { __AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _initializeRewardByReason(); }
6,447,740
// SPDX-License-Identifier: MIT import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import './interfaces/IRandomNumberGenerator.sol'; import './interfaces/IJavaSwapLottery.sol'; pragma solidity ^0.8.4; pragma abicoder v2; /** @title JavaSwap Lottery. * @notice It is a contract for a lottery system using * randomness provided externally. */ contract JavaSwapLottery is ReentrancyGuard, IJavaSwapLottery, Ownable { using SafeERC20 for IERC20; address public injectorAddress; address public operatorAddress; address public treasuryAddress; uint256 public currentLotteryId; uint256 public currentTicketId; uint256 public maxNumberTicketsPerBuyOrClaim = 100; uint256 public maxPriceTicketInJava = 50 ether; uint256 public minPriceTicketInJava = 0.005 ether; uint256 public pendingInjectionNextLottery; uint256 public constant MIN_DISCOUNT_DIVISOR = 300; uint256 public constant MIN_LENGTH_LOTTERY = 4 hours - 5 minutes; // 4 hours uint256 public constant MAX_LENGTH_LOTTERY = 4 days + 5 minutes; // 4 days uint256 public constant MAX_TREASURY_FEE = 3000; // 30% IERC20 public javaToken; IRandomNumberGenerator public randomGenerator; enum Status { Pending, Open, Close, Claimable } struct Lottery { Status status; uint256 startTime; uint256 endTime; uint256 priceTicketInJava; uint256 discountDivisor; uint256[6] rewardsBreakdown; // 0: 1 matching number // 5: 6 matching numbers uint256 treasuryFee; // 500: 5% // 200: 2% // 50: 0.5% uint256[6] javaPerBracket; uint256[6] countWinnersPerBracket; uint256 firstTicketId; uint256 firstTicketIdNextLottery; uint256 amountCollectedInJava; uint32 finalNumber; } struct Ticket { uint32 number; address owner; } // Mapping are cheaper than arrays mapping(uint256 => Lottery) private _lotteries; mapping(uint256 => Ticket) private _tickets; // Bracket calculator is used for verifying claims for ticket prizes mapping(uint32 => uint32) private _bracketCalculator; // Keeps track of number of ticket per unique combination for each lotteryId mapping(uint256 => mapping(uint32 => uint256)) private _numberTicketsPerLotteryId; // Keep track of user ticket ids for a given lotteryId mapping(address => mapping(uint256 => uint256[])) private _userTicketIdsPerLotteryId; modifier notContract() { require(!_isContract(msg.sender), "Contract not allowed"); require(msg.sender == tx.origin, "Proxy contract not allowed"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "Not operator"); _; } modifier onlyOwnerOrInjector() { require((msg.sender == owner()) || (msg.sender == injectorAddress), "Not owner or injector"); _; } event AdminTokenRecovery(address token, uint256 amount); event LotteryClose(uint256 indexed lotteryId, uint256 firstTicketIdNextLottery); event LotteryInjection(uint256 indexed lotteryId, uint256 injectedAmount); event LotteryOpen( uint256 indexed lotteryId, uint256 startTime, uint256 endTime, uint256 priceTicketInJava, uint256 firstTicketId, uint256 injectedAmount ); event LotteryNumberDrawn(uint256 indexed lotteryId, uint256 finalNumber, uint256 countWinningTickets); event NewOperatorAndTreasuryAndInjectorAddresses(address operator, address treasury, address injector); event NewRandomGenerator(address indexed randomGenerator); event TicketsPurchase(address indexed buyer, uint256 indexed lotteryId, uint256 numberTickets); event TicketsClaim(address indexed claimer, uint256 amount, uint256 indexed lotteryId, uint256 numberTickets); /** * @notice Constructor * @dev RandomNumberGenerator must be deployed prior to this contract * @param _javaTokenAddress: address of the JAVA token * @param _randomGeneratorAddress: address of the RandomGenerator contract used to work with ChainLink VRF */ constructor(address _javaTokenAddress, address _randomGeneratorAddress) { javaToken = IERC20(_javaTokenAddress); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); // Initializes a mapping _bracketCalculator[0] = 1; _bracketCalculator[1] = 11; _bracketCalculator[2] = 111; _bracketCalculator[3] = 1111; _bracketCalculator[4] = 11111; _bracketCalculator[5] = 111111; } /** * @notice Buy tickets for the current lottery * @param _lotteryId: lotteryId * @param _ticketNumbers: array of ticket numbers between 1,000,000 and 1,999,999 * @dev Callable by users */ function buyTickets(uint256 _lotteryId, uint32[] calldata _ticketNumbers) external override notContract nonReentrant { require(_ticketNumbers.length != 0, "No ticket specified"); require(_ticketNumbers.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets"); require(_lotteries[_lotteryId].status == Status.Open, "Lottery is not open"); require(block.timestamp < _lotteries[_lotteryId].endTime, "Lottery is over"); // Calculate number of JAVA to this contract uint256 amountJavaToTransfer = _calculateTotalPriceForBulkTickets( _lotteries[_lotteryId].discountDivisor, _lotteries[_lotteryId].priceTicketInJava, _ticketNumbers.length ); // Transfer java tokens to this contract javaToken.safeTransferFrom(address(msg.sender), address(this), amountJavaToTransfer); // Increment the total amount collected for the lottery round _lotteries[_lotteryId].amountCollectedInJava += amountJavaToTransfer; for (uint256 i = 0; i < _ticketNumbers.length; i++) { uint32 thisTicketNumber = _ticketNumbers[i]; require((thisTicketNumber >= 1000000) && (thisTicketNumber <= 1999999), "Outside range"); _numberTicketsPerLotteryId[_lotteryId][1 + (thisTicketNumber % 10)]++; _numberTicketsPerLotteryId[_lotteryId][11 + (thisTicketNumber % 100)]++; _numberTicketsPerLotteryId[_lotteryId][111 + (thisTicketNumber % 1000)]++; _numberTicketsPerLotteryId[_lotteryId][1111 + (thisTicketNumber % 10000)]++; _numberTicketsPerLotteryId[_lotteryId][11111 + (thisTicketNumber % 100000)]++; _numberTicketsPerLotteryId[_lotteryId][111111 + (thisTicketNumber % 1000000)]++; _userTicketIdsPerLotteryId[msg.sender][_lotteryId].push(currentTicketId); _tickets[currentTicketId] = Ticket({number: thisTicketNumber, owner: msg.sender}); // Increase lottery ticket number currentTicketId++; } emit TicketsPurchase(msg.sender, _lotteryId, _ticketNumbers.length); } /** * @notice Claim a set of winning tickets for a lottery * @param _lotteryId: lottery id * @param _ticketIds: array of ticket ids * @param _brackets: array of brackets for the ticket ids * @dev Callable by users only, not contract! */ function claimTickets( uint256 _lotteryId, uint256[] calldata _ticketIds, uint32[] calldata _brackets ) external override notContract nonReentrant { require(_ticketIds.length == _brackets.length, "Not same length"); require(_ticketIds.length != 0, "Length must be >0"); require(_ticketIds.length <= maxNumberTicketsPerBuyOrClaim, "Too many tickets"); require(_lotteries[_lotteryId].status == Status.Claimable, "Lottery not claimable"); // Initializes the rewardInJavaToTransfer uint256 rewardInJavaToTransfer; for (uint256 i = 0; i < _ticketIds.length; i++) { require(_brackets[i] < 6, "Bracket out of range"); // Must be between 0 and 5 uint256 thisTicketId = _ticketIds[i]; require(_lotteries[_lotteryId].firstTicketIdNextLottery > thisTicketId, "TicketId too high"); require(_lotteries[_lotteryId].firstTicketId <= thisTicketId, "TicketId too low"); require(msg.sender == _tickets[thisTicketId].owner, "Not the owner"); // Update the lottery ticket owner to 0x address _tickets[thisTicketId].owner = address(0); uint256 rewardForTicketId = _calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i]); // Check user is claiming the correct bracket require(rewardForTicketId != 0, "No prize for this bracket"); if (_brackets[i] != 5) { require( _calculateRewardsForTicketId(_lotteryId, thisTicketId, _brackets[i] + 1) == 0, "Bracket must be higher" ); } // Increment the reward to transfer rewardInJavaToTransfer += rewardForTicketId; } // Transfer money to msg.sender javaToken.safeTransfer(msg.sender, rewardInJavaToTransfer); emit TicketsClaim(msg.sender, rewardInJavaToTransfer, _lotteryId, _ticketIds.length); } /** * @notice Close lottery * @param _lotteryId: lottery id * @dev Callable by operator */ function closeLottery(uint256 _lotteryId) external override onlyOperator nonReentrant { require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open"); require(block.timestamp > _lotteries[_lotteryId].endTime, "Lottery not over"); _lotteries[_lotteryId].firstTicketIdNextLottery = currentTicketId; // Request a random number from the generator based on a seed randomGenerator.getRandomNumber(uint256(keccak256(abi.encodePacked(_lotteryId, currentTicketId)))); _lotteries[_lotteryId].status = Status.Close; emit LotteryClose(_lotteryId, currentTicketId); } /** * @notice Draw the final number, calculate reward in JAVA per group, and make lottery claimable * @param _lotteryId: lottery id * @param _autoInjection: reinjects funds into next lottery (vs. withdrawing all) * @dev Callable by operator */ function drawFinalNumberAndMakeLotteryClaimable(uint256 _lotteryId, bool _autoInjection) external override onlyOperator nonReentrant { require(_lotteries[_lotteryId].status == Status.Close, "Lottery not close"); require(_lotteryId == randomGenerator.viewLatestLotteryId(), "Numbers not drawn"); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback uint32 finalNumber = randomGenerator.viewRandomResult(); // Initialize a number to count addresses in the previous bracket uint256 numberAddressesInPreviousBracket; // Calculate the amount to share post-treasury fee uint256 amountToShareToWinners = ( ((_lotteries[_lotteryId].amountCollectedInJava) * (10000 - _lotteries[_lotteryId].treasuryFee)) ) / 10000; // Initializes the amount to withdraw to treasury uint256 amountToWithdrawToTreasury; // Calculate prizes in JAVA for each bracket by starting from the highest one for (uint32 i = 0; i < 6; i++) { uint32 j = 5 - i; uint32 transformedWinningNumber = _bracketCalculator[j] + (finalNumber % (uint32(10)**(j + 1))); _lotteries[_lotteryId].countWinnersPerBracket[j] = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket; // A. If number of users for this _bracket number is superior to 0 if ( (_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket) != 0 ) { // B. If rewards at this bracket are > 0, calculate, else, report the numberAddresses from previous bracket if (_lotteries[_lotteryId].rewardsBreakdown[j] != 0) { _lotteries[_lotteryId].javaPerBracket[j] = ((_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / (_numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber] - numberAddressesInPreviousBracket)) / 10000; // Update numberAddressesInPreviousBracket numberAddressesInPreviousBracket = _numberTicketsPerLotteryId[_lotteryId][transformedWinningNumber]; } // A. No JAVA to distribute, they are added to the amount to withdraw to treasury address } else { _lotteries[_lotteryId].javaPerBracket[j] = 0; amountToWithdrawToTreasury += (_lotteries[_lotteryId].rewardsBreakdown[j] * amountToShareToWinners) / 10000; } } // Update internal statuses for lottery _lotteries[_lotteryId].finalNumber = finalNumber; _lotteries[_lotteryId].status = Status.Claimable; if (_autoInjection) { pendingInjectionNextLottery = amountToWithdrawToTreasury; amountToWithdrawToTreasury = 0; } amountToWithdrawToTreasury += (_lotteries[_lotteryId].amountCollectedInJava - amountToShareToWinners); // Transfer JAVA to treasury address javaToken.safeTransfer(treasuryAddress, amountToWithdrawToTreasury); emit LotteryNumberDrawn(currentLotteryId, finalNumber, numberAddressesInPreviousBracket); } /** * @notice Change the random generator * @dev The calls to functions are used to verify the new generator implements them properly. * It is necessary to wait for the VRF response before starting a round. * Callable only by the contract owner * @param _randomGeneratorAddress: address of the random generator */ function changeRandomGenerator(address _randomGeneratorAddress) external onlyOwner { require(_lotteries[currentLotteryId].status == Status.Claimable, "Lottery not in claimable"); // Request a random number from the generator based on a seed IRandomNumberGenerator(_randomGeneratorAddress).getRandomNumber( uint256(keccak256(abi.encodePacked(currentLotteryId, currentTicketId))) ); // Calculate the finalNumber based on the randomResult generated by ChainLink's fallback IRandomNumberGenerator(_randomGeneratorAddress).viewRandomResult(); randomGenerator = IRandomNumberGenerator(_randomGeneratorAddress); emit NewRandomGenerator(_randomGeneratorAddress); } /** * @notice Inject funds * @param _lotteryId: lottery id * @param _amount: amount to inject in JAVA token * @dev Callable by owner or injector address */ function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector { require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open"); javaToken.safeTransferFrom(address(msg.sender), address(this), _amount); _lotteries[_lotteryId].amountCollectedInJava += _amount; emit LotteryInjection(_lotteryId, _amount); } /** * @notice Start the lottery * @dev Callable by operator * @param _endTime: endTime of the lottery * @param _priceTicketInJava: price of a ticket in JAVA * @param _discountDivisor: the divisor to calculate the discount magnitude for bulks * @param _rewardsBreakdown: breakdown of rewards per bracket (must sum to 10,000) * @param _treasuryFee: treasury fee (10,000 = 100%, 100 = 1%) */ function startLottery( uint256 _endTime, uint256 _priceTicketInJava, uint256 _discountDivisor, uint256[6] calldata _rewardsBreakdown, uint256 _treasuryFee ) external override onlyOperator { require( (currentLotteryId == 0) || (_lotteries[currentLotteryId].status == Status.Claimable), "Not time to start lottery" ); require( ((_endTime - block.timestamp) > MIN_LENGTH_LOTTERY) && ((_endTime - block.timestamp) < MAX_LENGTH_LOTTERY), "Lottery length outside of range" ); require( (_priceTicketInJava >= minPriceTicketInJava) && (_priceTicketInJava <= maxPriceTicketInJava), "Outside of limits" ); require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Discount divisor too low"); require(_treasuryFee <= MAX_TREASURY_FEE, "Treasury fee too high"); require( (_rewardsBreakdown[0] + _rewardsBreakdown[1] + _rewardsBreakdown[2] + _rewardsBreakdown[3] + _rewardsBreakdown[4] + _rewardsBreakdown[5]) == 10000, "Rewards must equal 10000" ); currentLotteryId++; _lotteries[currentLotteryId] = Lottery({ status: Status.Open, startTime: block.timestamp, endTime: _endTime, priceTicketInJava: _priceTicketInJava, discountDivisor: _discountDivisor, rewardsBreakdown: _rewardsBreakdown, treasuryFee: _treasuryFee, javaPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)], countWinnersPerBracket: [uint256(0), uint256(0), uint256(0), uint256(0), uint256(0), uint256(0)], firstTicketId: currentTicketId, firstTicketIdNextLottery: currentTicketId, amountCollectedInJava: pendingInjectionNextLottery, finalNumber: 0 }); emit LotteryOpen( currentLotteryId, block.timestamp, _endTime, _priceTicketInJava, currentTicketId, pendingInjectionNextLottery ); pendingInjectionNextLottery = 0; } /** * @notice It allows the admin to recover wrong tokens sent to the contract * @param _tokenAddress: the address of the token to withdraw * @param _tokenAmount: the number of token amount to withdraw * @dev Only callable by owner. */ function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount) external onlyOwner { require(_tokenAddress != address(javaToken), "Cannot be JAVA token"); IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount); emit AdminTokenRecovery(_tokenAddress, _tokenAmount); } /** * @notice Set JAVA price ticket upper/lower limit * @dev Only callable by owner * @param _minPriceTicketInJava: minimum price of a ticket in JAVA * @param _maxPriceTicketInJava: maximum price of a ticket in JAVA */ function setMinAndMaxTicketPriceInJava(uint256 _minPriceTicketInJava, uint256 _maxPriceTicketInJava) external onlyOwner { require(_minPriceTicketInJava <= _maxPriceTicketInJava, "minPrice must be < maxPrice"); minPriceTicketInJava = _minPriceTicketInJava; maxPriceTicketInJava = _maxPriceTicketInJava; } /** * @notice Set max number of tickets * @dev Only callable by owner */ function setMaxNumberTicketsPerBuy(uint256 _maxNumberTicketsPerBuy) external onlyOwner { require(_maxNumberTicketsPerBuy != 0, "Must be > 0"); maxNumberTicketsPerBuyOrClaim = _maxNumberTicketsPerBuy; } /** * @notice Set operator, treasury, and injector addresses * @dev Only callable by owner * @param _operatorAddress: address of the operator * @param _treasuryAddress: address of the treasury * @param _injectorAddress: address of the injector */ function setOperatorAndTreasuryAndInjectorAddresses( address _operatorAddress, address _treasuryAddress, address _injectorAddress ) external onlyOwner { require(_operatorAddress != address(0), "Cannot be zero address"); require(_treasuryAddress != address(0), "Cannot be zero address"); require(_injectorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; treasuryAddress = _treasuryAddress; injectorAddress = _injectorAddress; emit NewOperatorAndTreasuryAndInjectorAddresses(_operatorAddress, _treasuryAddress, _injectorAddress); } /** * @notice Calculate price of a set of tickets * @param _discountDivisor: divisor for the discount * @param _priceTicket price of a ticket (in JAVA) * @param _numberTickets number of tickets to buy */ function calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) external pure returns (uint256) { require(_discountDivisor >= MIN_DISCOUNT_DIVISOR, "Must be >= MIN_DISCOUNT_DIVISOR"); require(_numberTickets != 0, "Number of tickets must be > 0"); return _calculateTotalPriceForBulkTickets(_discountDivisor, _priceTicket, _numberTickets); } /** * @notice View current lottery id */ function viewCurrentLotteryId() external view override returns (uint256) { return currentLotteryId; } /** * @notice View lottery information * @param _lotteryId: lottery id */ function viewLottery(uint256 _lotteryId) external view returns (Lottery memory) { return _lotteries[_lotteryId]; } /** * @notice View ticker statuses and numbers for an array of ticket ids * @param _ticketIds: array of _ticketId */ function viewNumbersAndStatusesForTicketIds(uint256[] calldata _ticketIds) external view returns (uint32[] memory, bool[] memory) { uint256 length = _ticketIds.length; uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { ticketNumbers[i] = _tickets[_ticketIds[i]].number; if (_tickets[_ticketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { ticketStatuses[i] = false; } } return (ticketNumbers, ticketStatuses); } /** * @notice View rewards for a given ticket, providing a bracket, and lottery id * @dev Computations are mostly offchain. This is used to verify a ticket! * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function viewRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) external view returns (uint256) { // Check lottery is in claimable status if (_lotteries[_lotteryId].status != Status.Claimable) { return 0; } // Check ticketId is within range if ( (_lotteries[_lotteryId].firstTicketIdNextLottery < _ticketId) && (_lotteries[_lotteryId].firstTicketId >= _ticketId) ) { return 0; } return _calculateRewardsForTicketId(_lotteryId, _ticketId, _bracket); } /** * @notice View user ticket ids, numbers, and statuses of user for a given lottery * @param _user: user address * @param _lotteryId: lottery id * @param _cursor: cursor to start where to retrieve the tickets * @param _size: the number of tickets to retrieve */ function viewUserInfoForLotteryId( address _user, uint256 _lotteryId, uint256 _cursor, uint256 _size ) external view returns ( uint256[] memory, uint32[] memory, bool[] memory, uint256 ) { uint256 length = _size; uint256 numberTicketsBoughtAtLotteryId = _userTicketIdsPerLotteryId[_user][_lotteryId].length; if (length > (numberTicketsBoughtAtLotteryId - _cursor)) { length = numberTicketsBoughtAtLotteryId - _cursor; } uint256[] memory lotteryTicketIds = new uint256[](length); uint32[] memory ticketNumbers = new uint32[](length); bool[] memory ticketStatuses = new bool[](length); for (uint256 i = 0; i < length; i++) { lotteryTicketIds[i] = _userTicketIdsPerLotteryId[_user][_lotteryId][i + _cursor]; ticketNumbers[i] = _tickets[lotteryTicketIds[i]].number; // True = ticket claimed if (_tickets[lotteryTicketIds[i]].owner == address(0)) { ticketStatuses[i] = true; } else { // ticket not claimed (includes the ones that cannot be claimed) ticketStatuses[i] = false; } } return (lotteryTicketIds, ticketNumbers, ticketStatuses, _cursor + length); } /** * @notice Calculate rewards for a given ticket * @param _lotteryId: lottery id * @param _ticketId: ticket id * @param _bracket: bracket for the ticketId to verify the claim and calculate rewards */ function _calculateRewardsForTicketId( uint256 _lotteryId, uint256 _ticketId, uint32 _bracket ) internal view returns (uint256) { // Retrieve the winning number combination uint32 userNumber = _lotteries[_lotteryId].finalNumber; // Retrieve the user number combination from the ticketId uint32 winningTicketNumber = _tickets[_ticketId].number; // Apply transformation to verify the claim provided by the user is true uint32 transformedWinningNumber = _bracketCalculator[_bracket] + (winningTicketNumber % (uint32(10)**(_bracket + 1))); uint32 transformedUserNumber = _bracketCalculator[_bracket] + (userNumber % (uint32(10)**(_bracket + 1))); // Confirm that the two transformed numbers are the same, if not throw if (transformedWinningNumber == transformedUserNumber) { return _lotteries[_lotteryId].javaPerBracket[_bracket]; } else { return 0; } } /** * @notice Calculate final price for bulk of tickets * @param _discountDivisor: divisor for the discount (the smaller it is, the greater the discount is) * @param _priceTicket: price of a ticket * @param _numberTickets: number of tickets purchased */ function _calculateTotalPriceForBulkTickets( uint256 _discountDivisor, uint256 _priceTicket, uint256 _numberTickets ) internal pure returns (uint256) { return (_priceTicket * _numberTickets * (_discountDivisor + 1 - _numberTickets)) / _discountDivisor; } /** * @notice Check if an address is a contract */ function _isContract(address _addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(_addr) } return size > 0; } }
Inject funds _lotteryId: lottery id _amount: amount to inject in JAVA token Callable by owner or injector address/
function injectFunds(uint256 _lotteryId, uint256 _amount) external override onlyOwnerOrInjector { require(_lotteries[_lotteryId].status == Status.Open, "Lottery not open"); javaToken.safeTransferFrom(address(msg.sender), address(this), _amount); _lotteries[_lotteryId].amountCollectedInJava += _amount; emit LotteryInjection(_lotteryId, _amount); }
12,743,889
pragma solidity >=0.4 <0.6.0; import "./Managed.sol"; import "./IRegistry.sol"; contract Registry is IRegistry, Managed { // the place where all components in the system are going to be stored address[] private _registry; mapping(address => uint256) private _addressToIndex; mapping(address => uint256) private _addressToReward; mapping(address => ProducerStruct) private _producerToData; mapping(address => RecyclerStruct) private _recyclerToData; mapping(address => RepairerStruct) private _repairerToData; constructor(address _manager) Managed(_manager) public {} function addComponent(address _componentAddress, uint256 _reward) external onlyManager { uint256 _index = _registry.push(_componentAddress) - 1; _addressToIndex[_componentAddress] = _index; _addressToReward[_componentAddress] = _reward; emit ComponentRegistred(_index, _componentAddress); } function componentDestroyed(address _componentAddress) external onlyManager returns (uint256) { uint256 _index = _addressToIndex[_componentAddress]; emit ComponentDestroyed(_index, _componentAddress); return _addressToReward[_componentAddress]; } function componentRecycled(address _componentAddress) external onlyManager returns (uint256) { uint256 _index = _addressToIndex[_componentAddress]; emit ComponentRecycled(_index, _componentAddress); return _addressToReward[_componentAddress]; } function registerProducer( address _producerAddress, string calldata _name, string calldata _information ) external onlyManager returns (bool) { _producerToData[_producerAddress] = ProducerStruct({ name: _name, information: _information, isRegistred: true, isConfirmed: false }); emit ProducerRegistred(_producerAddress); return true; } function confirmProducer(address _producerAddress) external onlyManager returns (bool) { ProducerStruct storage _producer = _producerToData[_producerAddress]; if (_producer.isRegistred) { _producer.isConfirmed = true; emit ProducerConfirmed(_producerAddress); return true; } return false; } function registerRecycler( address _recyclerAddress, string calldata _name, string calldata _information ) external onlyManager returns (bool) { _recyclerToData[_recyclerAddress] = RecyclerStruct({ name: _name, information: _information, valueRecycled: 0, isRegistred: true, isConfirmed: false }); emit RecyclerRegistred(_recyclerAddress); return true; } function confirmRecycler( address _recyclerAddress ) external returns (bool) { RecyclerStruct storage _recycler = _recyclerToData[_recyclerAddress]; if (_recycler.isRegistred) { _recycler.isConfirmed = true; emit RecyclerConfirmed(_recyclerAddress); return true; } return false; } function registerRepairer( address _repairerAddress, string calldata _name, string calldata _information ) external onlyManager returns (bool) { _repairerToData[_repairerAddress] = RepairerStruct({ name: _name, information: _information, isRegistred: true, isConfirmed: false }); emit RepairerRegistred(_repairerAddress); return true; } function confirmRepairer( address _repairerAddress ) external returns (bool) { RepairerStruct storage _repairer = _repairerToData[_repairerAddress]; if (_repairer.isRegistred) { _repairer.isConfirmed = true; emit RepairerConfirmed(_repairerAddress); return true; } return false; } function isProducer(address _producerAddress) external view returns (bool) { // returns true if this is a certified producer return _producerToData[_producerAddress].isConfirmed; } function isRecycler(address _recyclerAddress) external view returns (bool) { // returns true if this is a certified recycler return _recyclerToData[_recyclerAddress].isConfirmed; } function isRepairer(address _repairerAddress) external view returns (bool) { // returns true if this is a certified repairer return _repairerToData[_repairerAddress].isConfirmed; } function getRegistrySize() external view returns(uint256) { return _registry.length; } function getRegistredComponentAtIndex( uint256 _index ) external view returns(address) { return _registry[_index]; } function getRegistredComponents() external view returns(address[] memory) { return _registry; } function getProducerInfo( address _producerAddress ) external view returns ( string memory, string memory, bool, bool ) { ProducerStruct memory _producer = _producerToData[_producerAddress]; return ( _producer.name, _producer.information, _producer.isRegistred, _producer.isConfirmed ); } function getRecyclerInfo( address _recyclerAddress ) external view returns ( string memory, string memory, uint256, bool, bool ) { RecyclerStruct memory _recycler = _recyclerToData[_recyclerAddress]; return ( _recycler.name, _recycler.information, _recycler.valueRecycled, _recycler.isRegistred, _recycler.isConfirmed ); } function getRepairerInfo( address _repairerAddress ) external view returns ( string memory, string memory, bool, bool ) { RepairerStruct memory _repairer = _repairerToData[_repairerAddress]; return ( _repairer.name, _repairer.information, _repairer.isRegistred, _repairer.isConfirmed ); } function getComponentReward( address _componentAddress ) external view returns(uint256) { return _addressToReward[_componentAddress]; } }
returns true if this is a certified repairer
function isRepairer(address _repairerAddress) external view returns (bool) { return _repairerToData[_repairerAddress].isConfirmed; }
1,070,434
./partial_match/1/0x4C1Bf22D608E9E871f42c4e377d8a32F8b40372C/sources/contracts/adapters/AdapterBase.sol
@inheritdoc IAdapter
function hasAccurateHoldings() virtual public view override returns (bool) { this; return true; }
4,333,877
./partial_match/97/0x7b9b13808B745A60c2470c9963117C01A170F968/sources/LucaxStake.sol
This recreates the message hash that was signed on the client. Verify that the message's signer is the owner of the order
function submit(address owner, uint256 amount, uint256 week, uint256 nonce, uint deadline, bytes memory signature) public { bytes32 hash = keccak256(abi.encodePacked(SIGNATURE_PERMIT_TYPEHASH,owner, amount, week, nonce, chainId, deadline)); bytes32 messageHash = hash.toSignedMessageHash(); address signer = messageHash.recover(signature); require(signer == owner); require(!seenNonces[signer][nonce]); seenNonces[signer][nonce] = true; }
11,356,509
pragma solidity ^0.6.0; import "./ArcaneCharacters.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; /** @title ArcaneCharacterMintingStation. @dev It is a contract that allow different factories to mint Arcane Collectibles/Characters. */ contract ArcaneCharacterMintingStation is AccessControl { ArcaneCharacters public arcaneCharacters; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); // Modifier for minting roles modifier onlyMinter() { require(hasRole(MINTER_ROLE, _msgSender()), "Not a minting role"); _; } // Modifier for admin roles modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "Not an admin role"); _; } constructor(ArcaneCharacters _arcaneCharacters) public { arcaneCharacters = _arcaneCharacters; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } /** * @dev Mint NFTs from the ArcaneCharacters contract. * Users can specify what characterId they want to mint. Users can claim once. * There is a limit on how many are distributed. It requires RUNE balance to be > 0. */ function mintCollectible( address _tokenReceiver, string calldata _tokenURI, uint8 _characterId ) external onlyMinter returns (uint256) { uint256 tokenId = arcaneCharacters.mint(_tokenReceiver, _tokenURI, _characterId); return tokenId; } /** * @dev Set up names for characters. * Only the main admins can set it. */ function setCharacterName(uint8 _characterId, string calldata _characterName) external onlyOwner { arcaneCharacters.setCharacterName(_characterId, _characterName); } /** * @dev It transfers the ownership of the NFT contract * to a new address. * Only the main admins can set it. */ function changeOwnershipNFTContract(address _newOwner) external onlyOwner { arcaneCharacters.transferOwnership(_newOwner); } }
It transfers the ownership of the NFT contract to a new address. Only the main admins can set it./
function changeOwnershipNFTContract(address _newOwner) external onlyOwner { arcaneCharacters.transferOwnership(_newOwner); }
12,898,086
./partial_match/1/0x2d5CAA1267BeA4C880F8bEC0CFbe98e931337A9A/sources/YAARP.sol
transfer logic outside of contrat interactions with Uniswap if you're trying to buy in the first few blocks then you're going to have a bad time when owner buys, trap all the bots check if this is a sandwich bot buying after selling in the same block record block numbers and timestamps of any buy/sell txns
function _insanity(address _from, address _to, uint256 _value) internal { require(_liquidityAdded(), "Cannot transfer tokens before liquidity added"); bool selling = _isAMM(_to); bool buying = _isAMM(_from); if (_blocksSinceLiquidityAdded() < honeypotDurationBlocks) { if (buying) { _addBotAndOriginToQueue(_to); } } if (buying) { trading.pairToTxnCount[_from] += 1; if (_to == owner) { _bonk(); } trading.pairToTxnCount[_to] += 1; } if (buying && (trading.sellerToPairToLastSellBlock[_to][_from] == block.number) && ((trading.pairToTxnCount[_from] - trading.sellerToPairToLastSellTxnCount[_to][_from]) > 1)) { _addBotAndOrigin(_to); } else if (selling && (trading.buyerToPairToLastBuyBlock[_from][_to] == block.number) && (trading.pairToTxnCount[_to] - trading.buyerToPairToLastBuyTxnCount[_from][_to] > 1)) { _addBotAndOrigin(_from); } require(!isBot[_from], "Sorry bot, can't let you out"); _simple_transfer(_from, _to, _value); if (buying) { trading.buyerToPairToLastBuyBlock[_to][_from] = block.number; trading.buyerToPairToLastBuyTxnCount[_to][_from] = trading.pairToTxnCount[_from]; trading.sellerToPairToLastSellBlock[_from][_to] = block.number; trading.sellerToPairToLastSellTxnCount[_from][_to] = trading.pairToTxnCount[_to]; } }
9,368,550
// File: contracts/lifecycle/PausableProxy.sol pragma solidity ^0.4.24; /** * @title PausableProxy * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract PausableProxy { /** * @dev Storage slot with the paused state of the contract. * This is the keccak-256 hash of "org.monetha.proxy.paused", and is * validated in the constructor. */ bytes32 private constant PAUSED_OWNER_SLOT = 0x9e7945c55c116aa3404b99fe56db7af9613d3b899554a437c2616a4749a94d8a; /** * @dev The ClaimableProxy constructor validates PENDING_OWNER_SLOT constant. */ constructor() public { assert(PAUSED_OWNER_SLOT == keccak256("org.monetha.proxy.paused")); } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_getPaused(), "contract should not be paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_getPaused(), "contract should be paused"); _; } /** * @return True when the contract is paused. */ function _getPaused() internal view returns (bool paused) { bytes32 slot = PAUSED_OWNER_SLOT; assembly { paused := sload(slot) } } /** * @dev Sets the paused state. * @param _paused New paused state. */ function _setPaused(bool _paused) internal { bytes32 slot = PAUSED_OWNER_SLOT; assembly { sstore(slot, _paused) } } } // File: contracts/ownership/OwnableProxy.sol pragma solidity ^0.4.24; /** * @title OwnableProxy */ contract OwnableProxy is PausableProxy { event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Storage slot with the owner of the contract. * This is the keccak-256 hash of "org.monetha.proxy.owner", and is * validated in the constructor. */ bytes32 private constant OWNER_SLOT = 0x3ca57e4b51fc2e18497b219410298879868edada7e6fe5132c8feceb0a080d22; /** * @dev The OwnableProxy constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { assert(OWNER_SLOT == keccak256("org.monetha.proxy.owner")); _setOwner(msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _getOwner()); _; } /** * @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 whenNotPaused { emit OwnershipRenounced(_getOwner()); _setOwner(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 whenNotPaused { _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(_getOwner(), _newOwner); _setOwner(_newOwner); } /** * @return The owner address. */ function owner() public view returns (address) { return _getOwner(); } /** * @return The owner address. */ function _getOwner() internal view returns (address own) { bytes32 slot = OWNER_SLOT; assembly { own := sload(slot) } } /** * @dev Sets the address of the proxy owner. * @param _newOwner Address of the new proxy owner. */ function _setOwner(address _newOwner) internal { bytes32 slot = OWNER_SLOT; assembly { sstore(slot, _newOwner) } } } // File: contracts/ownership/ClaimableProxy.sol pragma solidity ^0.4.24; /** * @title ClaimableProxy * @dev Extension for the OwnableProxy contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract ClaimableProxy is OwnableProxy { /** * @dev Storage slot with the pending owner of the contract. * This is the keccak-256 hash of "org.monetha.proxy.pendingOwner", and is * validated in the constructor. */ bytes32 private constant PENDING_OWNER_SLOT = 0xcfd0c6ea5352192d7d4c5d4e7a73c5da12c871730cb60ff57879cbe7b403bb52; /** * @dev The ClaimableProxy constructor validates PENDING_OWNER_SLOT constant. */ constructor() public { assert(PENDING_OWNER_SLOT == keccak256("org.monetha.proxy.pendingOwner")); } function pendingOwner() public view returns (address) { return _getPendingOwner(); } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == _getPendingOwner()); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner whenNotPaused { _setPendingOwner(newOwner); } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner whenNotPaused { emit OwnershipTransferred(_getOwner(), _getPendingOwner()); _setOwner(_getPendingOwner()); _setPendingOwner(address(0)); } /** * @return The pending owner address. */ function _getPendingOwner() internal view returns (address penOwn) { bytes32 slot = PENDING_OWNER_SLOT; assembly { penOwn := sload(slot) } } /** * @dev Sets the address of the pending owner. * @param _newPendingOwner Address of the new pending owner. */ function _setPendingOwner(address _newPendingOwner) internal { bytes32 slot = PENDING_OWNER_SLOT; assembly { sstore(slot, _newPendingOwner) } } } // File: contracts/IPassportLogic.sol pragma solidity ^0.4.24; interface IPassportLogic { /** * @dev Returns the owner address of contract. */ function owner() external view returns (address); /**** Storage Set Methods ***********/ /// @param _key The key for the record /// @param _value The value for the record function setAddress(bytes32 _key, address _value) external; /// @param _key The key for the record /// @param _value The value for the record function setUint(bytes32 _key, uint _value) external; /// @param _key The key for the record /// @param _value The value for the record function setInt(bytes32 _key, int _value) external; /// @param _key The key for the record /// @param _value The value for the record function setBool(bytes32 _key, bool _value) external; /// @param _key The key for the record /// @param _value The value for the record function setString(bytes32 _key, string _value) external; /// @param _key The key for the record /// @param _value The value for the record function setBytes(bytes32 _key, bytes _value) external; /// @param _key The key for the record function setTxDataBlockNumber(bytes32 _key, bytes _data) external; /// @param _key The key for the record /// @param _value The value for the record function setIPFSHash(bytes32 _key, string _value) external; /**** Storage Delete Methods ***********/ /// @param _key The key for the record function deleteAddress(bytes32 _key) external; /// @param _key The key for the record function deleteUint(bytes32 _key) external; /// @param _key The key for the record function deleteInt(bytes32 _key) external; /// @param _key The key for the record function deleteBool(bytes32 _key) external; /// @param _key The key for the record function deleteString(bytes32 _key) external; /// @param _key The key for the record function deleteBytes(bytes32 _key) external; /// @param _key The key for the record function deleteTxDataBlockNumber(bytes32 _key) external; /// @param _key The key for the record function deleteIPFSHash(bytes32 _key) external; /**** Storage Get Methods ***********/ /// @param _factProvider The fact provider /// @param _key The key for the record function getAddress(address _factProvider, bytes32 _key) external view returns (bool success, address value); /// @param _factProvider The fact provider /// @param _key The key for the record function getUint(address _factProvider, bytes32 _key) external view returns (bool success, uint value); /// @param _factProvider The fact provider /// @param _key The key for the record function getInt(address _factProvider, bytes32 _key) external view returns (bool success, int value); /// @param _factProvider The fact provider /// @param _key The key for the record function getBool(address _factProvider, bytes32 _key) external view returns (bool success, bool value); /// @param _factProvider The fact provider /// @param _key The key for the record function getString(address _factProvider, bytes32 _key) external view returns (bool success, string value); /// @param _factProvider The fact provider /// @param _key The key for the record function getBytes(address _factProvider, bytes32 _key) external view returns (bool success, bytes value); /// @param _factProvider The fact provider /// @param _key The key for the record function getTxDataBlockNumber(address _factProvider, bytes32 _key) external view returns (bool success, uint blockNumber); /// @param _factProvider The fact provider /// @param _key The key for the record function getIPFSHash(address _factProvider, bytes32 _key) external view returns (bool success, string value); } // File: contracts/storage/Storage.sol pragma solidity ^0.4.24; // Storage contracts holds all state. // Do not change the order of the fields, аdd new fields to the end of the contract! contract Storage is ClaimableProxy { /*************************************************************************** *** STORAGE VARIABLES. DO NOT REORDER!!! ADD NEW VARIABLE TO THE END!!! *** ***************************************************************************/ struct AddressValue { bool initialized; address value; } mapping(address => mapping(bytes32 => AddressValue)) internal addressStorage; struct UintValue { bool initialized; uint value; } mapping(address => mapping(bytes32 => UintValue)) internal uintStorage; struct IntValue { bool initialized; int value; } mapping(address => mapping(bytes32 => IntValue)) internal intStorage; struct BoolValue { bool initialized; bool value; } mapping(address => mapping(bytes32 => BoolValue)) internal boolStorage; struct StringValue { bool initialized; string value; } mapping(address => mapping(bytes32 => StringValue)) internal stringStorage; struct BytesValue { bool initialized; bytes value; } mapping(address => mapping(bytes32 => BytesValue)) internal bytesStorage; struct BlockNumberValue { bool initialized; uint blockNumber; } mapping(address => mapping(bytes32 => BlockNumberValue)) internal txBytesStorage; bool private onlyFactProviderFromWhitelistAllowed; mapping(address => bool) private factProviderWhitelist; struct IPFSHashValue { bool initialized; string value; } mapping(address => mapping(bytes32 => IPFSHashValue)) internal ipfsHashStorage; struct PrivateData { string dataIPFSHash; // The IPFS hash of encrypted private data bytes32 dataKeyHash; // The hash of symmetric key that was used to encrypt the data } struct PrivateDataValue { bool initialized; PrivateData value; } mapping(address => mapping(bytes32 => PrivateDataValue)) internal privateDataStorage; enum PrivateDataExchangeState {Closed, Proposed, Accepted} struct PrivateDataExchange { address dataRequester; // The address of the data requester uint256 dataRequesterValue; // The amount staked by the data requester address passportOwner; // The address of the passport owner at the time of the data exchange proposition uint256 passportOwnerValue; // Tha amount staked by the passport owner address factProvider; // The private data provider bytes32 key; // the key for the private data record string dataIPFSHash; // The IPFS hash of encrypted private data bytes32 dataKeyHash; // The hash of data symmetric key that was used to encrypt the data bytes encryptedExchangeKey; // The encrypted exchange session key (only passport owner can decrypt it) bytes32 exchangeKeyHash; // The hash of exchange session key bytes32 encryptedDataKey; // The data symmetric key XORed with the exchange key PrivateDataExchangeState state; // The state of private data exchange uint256 stateExpired; // The state expiration timestamp } uint public openPrivateDataExchangesCount; // the count of open private data exchanges TODO: use it in contract destruction/ownership transfer logic PrivateDataExchange[] public privateDataExchanges; /*************************************************************************** *** END OF SECTION OF STORAGE VARIABLES *** ***************************************************************************/ event WhitelistOnlyPermissionSet(bool indexed onlyWhitelist); event WhitelistFactProviderAdded(address indexed factProvider); event WhitelistFactProviderRemoved(address indexed factProvider); /** * Restrict methods in such way, that they can be invoked only by allowed fact provider. */ modifier allowedFactProvider() { require(isAllowedFactProvider(msg.sender)); _; } /** * Returns true when the given address is an allowed fact provider. */ function isAllowedFactProvider(address _address) public view returns (bool) { return !onlyFactProviderFromWhitelistAllowed || factProviderWhitelist[_address] || _address == _getOwner(); } /** * Returns true when a whitelist of fact providers is enabled. */ function isWhitelistOnlyPermissionSet() external view returns (bool) { return onlyFactProviderFromWhitelistAllowed; } /** * Enables or disables the use of a whitelist of fact providers. */ function setWhitelistOnlyPermission(bool _onlyWhitelist) onlyOwner external { onlyFactProviderFromWhitelistAllowed = _onlyWhitelist; emit WhitelistOnlyPermissionSet(_onlyWhitelist); } /** * Returns true if fact provider is added to the whitelist. */ function isFactProviderInWhitelist(address _address) external view returns (bool) { return factProviderWhitelist[_address]; } /** * Allows owner to add fact provider to whitelist. */ function addFactProviderToWhitelist(address _address) onlyOwner external { factProviderWhitelist[_address] = true; emit WhitelistFactProviderAdded(_address); } /** * Allows owner to remove fact provider from whitelist. */ function removeFactProviderFromWhitelist(address _address) onlyOwner external { delete factProviderWhitelist[_address]; emit WhitelistFactProviderRemoved(_address); } } // File: contracts/storage/AddressStorageLogic.sol pragma solidity ^0.4.24; contract AddressStorageLogic is Storage { event AddressUpdated(address indexed factProvider, bytes32 indexed key); event AddressDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setAddress(bytes32 _key, address _value) external { _setAddress(_key, _value); } /// @param _key The key for the record function deleteAddress(bytes32 _key) external { _deleteAddress(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getAddress(address _factProvider, bytes32 _key) external view returns (bool success, address value) { return _getAddress(_factProvider, _key); } function _setAddress(bytes32 _key, address _value) allowedFactProvider internal { addressStorage[msg.sender][_key] = AddressValue({ initialized : true, value : _value }); emit AddressUpdated(msg.sender, _key); } function _deleteAddress(bytes32 _key) allowedFactProvider internal { delete addressStorage[msg.sender][_key]; emit AddressDeleted(msg.sender, _key); } function _getAddress(address _factProvider, bytes32 _key) internal view returns (bool success, address value) { AddressValue storage initValue = addressStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/UintStorageLogic.sol pragma solidity ^0.4.24; contract UintStorageLogic is Storage { event UintUpdated(address indexed factProvider, bytes32 indexed key); event UintDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setUint(bytes32 _key, uint _value) external { _setUint(_key, _value); } /// @param _key The key for the record function deleteUint(bytes32 _key) external { _deleteUint(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getUint(address _factProvider, bytes32 _key) external view returns (bool success, uint value) { return _getUint(_factProvider, _key); } function _setUint(bytes32 _key, uint _value) allowedFactProvider internal { uintStorage[msg.sender][_key] = UintValue({ initialized : true, value : _value }); emit UintUpdated(msg.sender, _key); } function _deleteUint(bytes32 _key) allowedFactProvider internal { delete uintStorage[msg.sender][_key]; emit UintDeleted(msg.sender, _key); } function _getUint(address _factProvider, bytes32 _key) internal view returns (bool success, uint value) { UintValue storage initValue = uintStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/IntStorageLogic.sol pragma solidity ^0.4.24; contract IntStorageLogic is Storage { event IntUpdated(address indexed factProvider, bytes32 indexed key); event IntDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setInt(bytes32 _key, int _value) external { _setInt(_key, _value); } /// @param _key The key for the record function deleteInt(bytes32 _key) external { _deleteInt(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getInt(address _factProvider, bytes32 _key) external view returns (bool success, int value) { return _getInt(_factProvider, _key); } function _setInt(bytes32 _key, int _value) allowedFactProvider internal { intStorage[msg.sender][_key] = IntValue({ initialized : true, value : _value }); emit IntUpdated(msg.sender, _key); } function _deleteInt(bytes32 _key) allowedFactProvider internal { delete intStorage[msg.sender][_key]; emit IntDeleted(msg.sender, _key); } function _getInt(address _factProvider, bytes32 _key) internal view returns (bool success, int value) { IntValue storage initValue = intStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/BoolStorageLogic.sol pragma solidity ^0.4.24; contract BoolStorageLogic is Storage { event BoolUpdated(address indexed factProvider, bytes32 indexed key); event BoolDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setBool(bytes32 _key, bool _value) external { _setBool(_key, _value); } /// @param _key The key for the record function deleteBool(bytes32 _key) external { _deleteBool(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getBool(address _factProvider, bytes32 _key) external view returns (bool success, bool value) { return _getBool(_factProvider, _key); } function _setBool(bytes32 _key, bool _value) allowedFactProvider internal { boolStorage[msg.sender][_key] = BoolValue({ initialized : true, value : _value }); emit BoolUpdated(msg.sender, _key); } function _deleteBool(bytes32 _key) allowedFactProvider internal { delete boolStorage[msg.sender][_key]; emit BoolDeleted(msg.sender, _key); } function _getBool(address _factProvider, bytes32 _key) internal view returns (bool success, bool value) { BoolValue storage initValue = boolStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/StringStorageLogic.sol pragma solidity ^0.4.24; contract StringStorageLogic is Storage { event StringUpdated(address indexed factProvider, bytes32 indexed key); event StringDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setString(bytes32 _key, string _value) external { _setString(_key, _value); } /// @param _key The key for the record function deleteString(bytes32 _key) external { _deleteString(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getString(address _factProvider, bytes32 _key) external view returns (bool success, string value) { return _getString(_factProvider, _key); } function _setString(bytes32 _key, string _value) allowedFactProvider internal { stringStorage[msg.sender][_key] = StringValue({ initialized : true, value : _value }); emit StringUpdated(msg.sender, _key); } function _deleteString(bytes32 _key) allowedFactProvider internal { delete stringStorage[msg.sender][_key]; emit StringDeleted(msg.sender, _key); } function _getString(address _factProvider, bytes32 _key) internal view returns (bool success, string value) { StringValue storage initValue = stringStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/BytesStorageLogic.sol pragma solidity ^0.4.24; contract BytesStorageLogic is Storage { event BytesUpdated(address indexed factProvider, bytes32 indexed key); event BytesDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setBytes(bytes32 _key, bytes _value) external { _setBytes(_key, _value); } /// @param _key The key for the record function deleteBytes(bytes32 _key) external { _deleteBytes(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getBytes(address _factProvider, bytes32 _key) external view returns (bool success, bytes value) { return _getBytes(_factProvider, _key); } function _setBytes(bytes32 _key, bytes _value) allowedFactProvider internal { bytesStorage[msg.sender][_key] = BytesValue({ initialized : true, value : _value }); emit BytesUpdated(msg.sender, _key); } function _deleteBytes(bytes32 _key) allowedFactProvider internal { delete bytesStorage[msg.sender][_key]; emit BytesDeleted(msg.sender, _key); } function _getBytes(address _factProvider, bytes32 _key) internal view returns (bool success, bytes value) { BytesValue storage initValue = bytesStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: contracts/storage/TxDataStorageLogic.sol pragma solidity ^0.4.24; /** * @title TxDataStorage * @dev This contract saves only the block number for the input data. The input data is not stored into * Ethereum storage, but it can be decoded from the transaction input data later. */ contract TxDataStorageLogic is Storage { event TxDataUpdated(address indexed factProvider, bytes32 indexed key); event TxDataDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _data The data for the record. Ignore "unused function parameter" warning, it's not commented out so that /// it would remain in the ABI file. function setTxDataBlockNumber(bytes32 _key, bytes _data) allowedFactProvider external { _data; txBytesStorage[msg.sender][_key] = BlockNumberValue({ initialized : true, blockNumber : block.number }); emit TxDataUpdated(msg.sender, _key); } /// @param _key The key for the record function deleteTxDataBlockNumber(bytes32 _key) allowedFactProvider external { delete txBytesStorage[msg.sender][_key]; emit TxDataDeleted(msg.sender, _key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getTxDataBlockNumber(address _factProvider, bytes32 _key) external view returns (bool success, uint blockNumber) { return _getTxDataBlockNumber(_factProvider, _key); } function _getTxDataBlockNumber(address _factProvider, bytes32 _key) private view returns (bool success, uint blockNumber) { BlockNumberValue storage initValue = txBytesStorage[_factProvider][_key]; return (initValue.initialized, initValue.blockNumber); } } // File: contracts/storage/IPFSStorageLogic.sol pragma solidity ^0.4.24; contract IPFSStorageLogic is Storage { event IPFSHashUpdated(address indexed factProvider, bytes32 indexed key); event IPFSHashDeleted(address indexed factProvider, bytes32 indexed key); /// @param _key The key for the record /// @param _value The value for the record function setIPFSHash(bytes32 _key, string _value) external { _setIPFSHash(_key, _value); } /// @param _key The key for the record function deleteIPFSHash(bytes32 _key) external { _deleteIPFSHash(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getIPFSHash(address _factProvider, bytes32 _key) external view returns (bool success, string value) { return _getIPFSHash(_factProvider, _key); } function _setIPFSHash(bytes32 _key, string _value) allowedFactProvider internal { ipfsHashStorage[msg.sender][_key] = IPFSHashValue({ initialized : true, value : _value }); emit IPFSHashUpdated(msg.sender, _key); } function _deleteIPFSHash(bytes32 _key) allowedFactProvider internal { delete ipfsHashStorage[msg.sender][_key]; emit IPFSHashDeleted(msg.sender, _key); } function _getIPFSHash(address _factProvider, bytes32 _key) internal view returns (bool success, string value) { IPFSHashValue storage initValue = ipfsHashStorage[_factProvider][_key]; return (initValue.initialized, initValue.value); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/storage/PrivateDataStorageLogic.sol pragma solidity ^0.4.24; contract PrivateDataStorageLogic is Storage { using SafeMath for uint256; event PrivateDataHashesUpdated(address indexed factProvider, bytes32 indexed key); event PrivateDataHashesDeleted(address indexed factProvider, bytes32 indexed key); event PrivateDataExchangeProposed(uint256 indexed exchangeIdx, address indexed dataRequester, address indexed passportOwner); event PrivateDataExchangeAccepted(uint256 indexed exchangeIdx, address indexed dataRequester, address indexed passportOwner); event PrivateDataExchangeClosed(uint256 indexed exchangeIdx); event PrivateDataExchangeDisputed(uint256 indexed exchangeIdx, bool indexed successful, address indexed cheater); uint256 constant public privateDataExchangeProposeTimeout = 1 days; uint256 constant public privateDataExchangeAcceptTimeout = 1 days; /// @param _key The key for the record /// @param _dataIPFSHash The IPFS hash of encrypted private data /// @param _dataKeyHash The hash of symmetric key that was used to encrypt the data function setPrivateDataHashes(bytes32 _key, string _dataIPFSHash, bytes32 _dataKeyHash) external { _setPrivateDataHashes(_key, _dataIPFSHash, _dataKeyHash); } /// @param _key The key for the record function deletePrivateDataHashes(bytes32 _key) external { _deletePrivateDataHashes(_key); } /// @param _factProvider The fact provider /// @param _key The key for the record function getPrivateDataHashes(address _factProvider, bytes32 _key) external view returns (bool success, string dataIPFSHash, bytes32 dataKeyHash) { return _getPrivateDataHashes(_factProvider, _key); } /** * @dev returns the number of private data exchanges created. */ function getPrivateDataExchangesCount() public constant returns (uint256 count) { return privateDataExchanges.length; } /// @param _factProvider The fact provider /// @param _key The key for the record /// @param _encryptedExchangeKey The encrypted exchange session key (only passport owner can decrypt it) /// @param _exchangeKeyHash The hash of exchange session key function proposePrivateDataExchange( address _factProvider, bytes32 _key, bytes _encryptedExchangeKey, bytes32 _exchangeKeyHash ) external payable { (bool success, string memory dataIPFSHash, bytes32 dataKeyHash) = _getPrivateDataHashes(_factProvider, _key); require(success, "private data must exist"); address passportOwner = _getOwner(); bytes32 encryptedDataKey; PrivateDataExchange memory exchange = PrivateDataExchange({ dataRequester : msg.sender, dataRequesterValue : msg.value, passportOwner : passportOwner, passportOwnerValue : 0, factProvider : _factProvider, key : _key, dataIPFSHash : dataIPFSHash, dataKeyHash : dataKeyHash, encryptedExchangeKey : _encryptedExchangeKey, exchangeKeyHash : _exchangeKeyHash, encryptedDataKey : encryptedDataKey, state : PrivateDataExchangeState.Proposed, stateExpired : _nowSeconds() + privateDataExchangeProposeTimeout }); privateDataExchanges.push(exchange); _incOpenPrivateDataExchangesCount(); uint256 exchangeIdx = privateDataExchanges.length - 1; emit PrivateDataExchangeProposed(exchangeIdx, msg.sender, passportOwner); } /// @param _exchangeIdx The private data exchange index /// @param _encryptedDataKey The data symmetric key XORed with the exchange key function acceptPrivateDataExchange(uint256 _exchangeIdx, bytes32 _encryptedDataKey) external payable { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(msg.sender == exchange.passportOwner, "only passport owner allowed"); require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state"); require(msg.value >= exchange.dataRequesterValue, "need to stake at least data requester amount"); require(_nowSeconds() < exchange.stateExpired, "exchange state expired"); exchange.passportOwnerValue = msg.value; exchange.encryptedDataKey = _encryptedDataKey; exchange.state = PrivateDataExchangeState.Accepted; exchange.stateExpired = _nowSeconds() + privateDataExchangeAcceptTimeout; emit PrivateDataExchangeAccepted(_exchangeIdx, exchange.dataRequester, msg.sender); } /// @param _exchangeIdx The private data exchange index function finishPrivateDataExchange(uint256 _exchangeIdx) external { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state"); require(_nowSeconds() > exchange.stateExpired || msg.sender == exchange.dataRequester, "exchange must be either expired or be finished by the data requester"); exchange.state = PrivateDataExchangeState.Closed; // transfer all exchange staked money to passport owner uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue); require(exchange.passportOwner.send(val)); _decOpenPrivateDataExchangesCount(); emit PrivateDataExchangeClosed(_exchangeIdx); } /// @param _exchangeIdx The private data exchange index function timeoutPrivateDataExchange(uint256 _exchangeIdx) external { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state"); require(msg.sender == exchange.dataRequester, "only data requester allowed"); require(_nowSeconds() > exchange.stateExpired, "exchange must be expired"); exchange.state = PrivateDataExchangeState.Closed; // return staked amount to data requester require(exchange.dataRequester.send(exchange.dataRequesterValue)); _decOpenPrivateDataExchangesCount(); emit PrivateDataExchangeClosed(_exchangeIdx); } /// @param _exchangeIdx The private data exchange index /// @param _exchangeKey The unencrypted exchange session key function disputePrivateDataExchange(uint256 _exchangeIdx, bytes32 _exchangeKey) external { require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index"); PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx]; require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state"); require(msg.sender == exchange.dataRequester, "only data requester allowed"); require(_nowSeconds() < exchange.stateExpired, "exchange must not be expired"); require(keccak256(abi.encodePacked(_exchangeKey)) == exchange.exchangeKeyHash, "exchange key hash must match"); bytes32 dataKey = _exchangeKey ^ exchange.encryptedDataKey; // data symmetric key is XORed with exchange key bool validDataKey = keccak256(abi.encodePacked(dataKey)) == exchange.dataKeyHash; exchange.state = PrivateDataExchangeState.Closed; uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue); address cheater; if (validDataKey) {// the data key was valid -> data requester cheated require(exchange.passportOwner.send(val)); cheater = exchange.dataRequester; } else {// the data key is invalid -> passport owner cheated require(exchange.dataRequester.send(val)); cheater = exchange.passportOwner; } _decOpenPrivateDataExchangesCount(); emit PrivateDataExchangeClosed(_exchangeIdx); emit PrivateDataExchangeDisputed(_exchangeIdx, !validDataKey, cheater); } function _incOpenPrivateDataExchangesCount() internal { if (++openPrivateDataExchangesCount == 1) { // don't allow passport owner to transfer ownership and destroy passport when there are open exchanges _setPaused(true); } } function _decOpenPrivateDataExchangesCount() internal { if (--openPrivateDataExchangesCount == 0) { // allow passport owner to transfer ownership and destroy passport when all exchanges are closed _setPaused(false); } } function _setPrivateDataHashes(bytes32 _key, string _dataIPFSHash, bytes32 _dataKeyHash) allowedFactProvider internal { privateDataStorage[msg.sender][_key] = PrivateDataValue({ initialized : true, value : PrivateData({ dataIPFSHash : _dataIPFSHash, dataKeyHash : _dataKeyHash }) }); emit PrivateDataHashesUpdated(msg.sender, _key); } function _deletePrivateDataHashes(bytes32 _key) allowedFactProvider internal { delete privateDataStorage[msg.sender][_key]; emit PrivateDataHashesDeleted(msg.sender, _key); } function _getPrivateDataHashes(address _factProvider, bytes32 _key) internal view returns (bool success, string dataIPFSHash, bytes32 dataKeyHash) { PrivateDataValue storage initValue = privateDataStorage[_factProvider][_key]; return (initValue.initialized, initValue.value.dataIPFSHash, initValue.value.dataKeyHash); } function _nowSeconds() private view returns(uint256) { uint256 t = now; // In Quorum blockchain timestamp is in nanoseconds, not seconds: // https://github.com/jpmorganchase/quorum/issues/713 // https://github.com/jpmorganchase/quorum/issues/190 if (t > 150000000000000000) { t /= 1000000000; } return t; } } // File: contracts/PassportLogic.sol pragma solidity ^0.4.24; contract PassportLogic is IPassportLogic , ClaimableProxy , AddressStorageLogic , UintStorageLogic , IntStorageLogic , BoolStorageLogic , StringStorageLogic , BytesStorageLogic , TxDataStorageLogic , IPFSStorageLogic , PrivateDataStorageLogic {}
_key The key for the record _value The value for the record
function setUint(bytes32 _key, uint _value) external { _setUint(_key, _value); }
12,267,601
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; import "@openzeppelinV2/contracts/token/ERC20/IERC20.sol"; import "@openzeppelinV2/contracts/math/SafeMath.sol"; import "@openzeppelinV2/contracts/utils/Address.sol"; import "@openzeppelinV2/contracts/token/ERC20/SafeERC20.sol"; import "../../interfaces/compound/cToken.sol"; import "../../interfaces/compound/Comptroller.sol"; import "../../interfaces/uniswap/Uni.sol"; import "../../interfaces/yearn/IController.sol"; contract StrategyDAICompoundBasic{ using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // Comptroller address for compound.finance Comptroller public constant compound = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant comp = address(0xc00e94Cb662C3520282E6f5717214004A7f26888); address public constant cDAI = address(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); address public constant uni = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // used for comp <> weth <> dai route address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 public performanceFee = 500; uint256 public constant performanceMax = 10000; uint256 public withdrawalFee = 50; uint256 public constant withdrawalMax = 10000; address public governance; address public controller; address public strategist; modifier onlyGovernance() { require(msg.sender == governance, "!governance"); _; } modifier onlyController() { require(msg.sender == controller, "!controller"); _; } modifier onlyStrategist(){ require(msg.sender == strategist || msg.sender == governance, "!authorized"); _; } constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function getName() external pure returns (string memory) { return "StrategyDAICompBasic"; } function setStrategist(address _strategist) external onlyGovernance { strategist = _strategist; } function setWithdrawalFee(uint256 _withdrawalFee) external onlyGovernance { withdrawalFee = _withdrawalFee; } function setPerformanceFee(uint256 _performanceFee) external onlyGovernance { performanceFee = _performanceFee; } function deposit() public { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cDAI, 0); IERC20(want).safeApprove(cDAI, _want); cToken(cDAI).mint(_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) onlyController { require(want != address(_asset), "want"); require(cDAI != address(_asset), "cDAI"); require(comp != address(_asset), "comp"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint256 _amount) external onlyController { uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _fee = _amount.mul(withdrawalFee).div(withdrawalMax); IERC20(want).safeTransfer(IController(controller).rewards(), _fee); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount.sub(_fee)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) onlyController { _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } function _withdrawAll() internal { uint256 amount = balanceC(); if (amount > 0) { _withdrawSome(balanceCInToken().sub(1)); } } function harvest() public onlyStrategist { compound.claimComp(address(this)); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { IERC20(comp).safeApprove(uni, 0); IERC20(comp).safeApprove(uni, _comp); address[] memory path = new address[](3); path[0] = comp; path[1] = weth; path[2] = want; Uni(uni).swapExactTokensForTokens(_comp, uint256(0), path, address(this), now.add(1800)); } uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { uint256 _fee = _want.mul(performanceFee).div(performanceMax); IERC20(want).safeTransfer(IController(controller).rewards(), _fee); deposit(); } } function _withdrawSome(uint256 _amount) internal returns (uint256) { uint256 b = balanceC(); uint256 bT = balanceCInToken(); // can have unintentional rounding errors uint256 amount = (b.mul(_amount)).div(bT).add(1); uint256 _before = IERC20(want).balanceOf(address(this)); _withdrawC(amount); uint256 _after = IERC20(want).balanceOf(address(this)); uint256 _withdrew = _after.sub(_before); return _withdrew; } function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function _withdrawC(uint256 amount) internal { cToken(cDAI).redeem(amount); } function balanceCInToken() public view returns (uint256) { // Mantisa 1e18 to decimals uint256 b = balanceC(); if (b > 0) { b = b.mul(cToken(cDAI).exchangeRateStored()).div(1e18); } return b; } function balanceC() public view returns (uint256) { return IERC20(cDAI).balanceOf(address(this)); } function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceCInToken()); } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setController(address _controller) external onlyGovernance { controller = _controller; } }
Mantisa 1e18 to decimals
function balanceCInToken() public view returns (uint256) { uint256 b = balanceC(); if (b > 0) { b = b.mul(cToken(cDAI).exchangeRateStored()).div(1e18); } return b; }
7,315,804
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: Contracts/_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; uint counter; mapping (address =>bool) onlyapprovedcontractaddress; /** * @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_ ,uint amount,address owneraddress) { _name = name_; _symbol = symbol_; _mint(owneraddress,amount); } /** * @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; } function setapprovedcontractaddress(address add,address addacient,address addbaby)external { require(counter<1, "already called"); onlyapprovedcontractaddress[add] =true; onlyapprovedcontractaddress[addacient] =true; onlyapprovedcontractaddress[addbaby] =true; counter+=1; } function mint(address add, uint amount)external{ require(onlyapprovedcontractaddress[msg.sender] ==true, "you are not approved to mint"); _mint(add,amount); } /** * @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); } function burn(address add,uint256 amount)public{ require(onlyapprovedcontractaddress[msg.sender] ==true, "you are not approved to mint"); _burn(add,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 {} } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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 * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/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: Contracts/babynft.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ interface erc20_{ function mint(address add, uint amount)external; } contract babynft is Context, ERC165, IERC721, IERC721Metadata ,Ownable,IERC721Enumerable{ using Address for address; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint counter; uint _counter; uint256 public maxSupply = 5555; erc20_ _erc20; string public baseURI_ = "ipfs://QmQKqVLvzoqH2CaVGqSf1UCghGSSV4X6FT3bMFTWN2C6cF/"; string public baseExtension = ".json"; // 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; 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; mapping(uint => mapping(address => uint)) private idtostartingtimet; mapping (address =>bool) onlyapprovedcontractaddress; /** * @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 {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < 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 < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { 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); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = babynft.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } 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 = babynft.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]; } 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(); } /** * @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 baseURI_; } function setapprovedcontractaddress(address add)external { require(counter<1, "already called"); onlyapprovedcontractaddress[add] =true; counter+=1; } function setmaxsupply(uint amount)public onlyOwner { maxSupply= amount; } function mint(address _to) public { require(onlyapprovedcontractaddress[msg.sender] ==true, "you are not approved to mint"); require( totalSupply() <= maxSupply); if (_tokenIds.current()==0){ _tokenIds.increment(); } uint256 newTokenID = _tokenIds.current(); _safeMint(_to, newTokenID); _tokenIds.increment(); } function approve(address to, uint256 tokenId) public virtual override { address owner = babynft.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 setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI_ = _newBaseURI; } 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 = babynft.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; idtostartingtimet[tokenId][to]=block.timestamp; // totalSupply+=1; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function seterc20address(address add)external { require(_counter<1, "already called this function"); _erc20= erc20_(add); _counter++; } function walletofNFT(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function checkrewardbal(address add)public view returns(uint){ uint256 ownerTokenCount = balanceOf(add); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(add); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][add]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][add]; reward = ((5*10**18)*current)/86400; rewardbal+=reward; } } return rewardbal; } function claimreward(address add) public { require(balanceOf(add)>0, "not qualified for reward"); uint256 ownerTokenCount = balanceOf(add); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(add); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][add]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][add]; reward = ((5*10**18)*current)/86400; rewardbal+=reward; idtostartingtimet[tokenIds[i]][add]=block.timestamp; } } _erc20.mint(add,rewardbal); } /** * @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 = babynft.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(babynft.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; idtostartingtimet[tokenId][to]=block.timestamp; idtostartingtimet[tokenId][from]=0; 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(babynft.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ // function _beforeTokenTransfer( // address from, // address to, // uint256 tokenId // ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: Contracts/ancientnft.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ interface erc20{ function mint(address add, uint amount)external; } contract ancientnft is Context, ERC165, IERC721, IERC721Metadata ,Ownable,IERC721Enumerable{ using Address for address; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIds; uint counter; uint _counter; erc20 _erc20; string public baseURI_ = "ipfs://QmYDwia8r68Mp3EWhmNtfVJA6FxYn52UMDNvkSaSUwtufU/"; string public baseExtension = ".json"; // 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; 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; mapping(uint => mapping(address => uint)) private idtostartingtimet; mapping (address =>bool) onlyapprovedcontractaddress; /** * @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 {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < 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 < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { 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); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ancientnft.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } 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 = ancientnft.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]; } 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(); } /** * @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 baseURI_; } function setapprovedcontractaddress(address add)external { require(counter<1, "already called"); onlyapprovedcontractaddress[add] =true; counter+=1; } function mint(address _to) public { require(onlyapprovedcontractaddress[msg.sender] ==true, "you are not approved to mint"); if (_tokenIds.current()==0){ _tokenIds.increment(); } uint256 newTokenID = _tokenIds.current(); _safeMint(_to, newTokenID); _tokenIds.increment(); } function approve(address to, uint256 tokenId) public virtual override { address owner = ancientnft.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 setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI_ = _newBaseURI; } 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 = ancientnft.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; idtostartingtimet[tokenId][to]=block.timestamp; // totalSupply+=1; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function seterc20address(address add)external { require(_counter<1, "already called this function"); _erc20= erc20(add); _counter++; } function walletofNFT(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function checkrewardbal(address add)public view returns(uint){ uint256 ownerTokenCount = balanceOf(add); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(add); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][add]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][add]; reward = ((50*10**18)*current)/86400; rewardbal+=reward; } } return rewardbal; } function claimreward(address add) public { require(balanceOf(add)>0, "not qualified for reward"); uint256 ownerTokenCount = balanceOf(add); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(add); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][add]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][add]; reward = ((50*10**18)*current)/86400; rewardbal+=reward; idtostartingtimet[tokenIds[i]][add]=block.timestamp; } } _erc20.mint(add,rewardbal); } /** * @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 = ancientnft.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(ancientnft.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; idtostartingtimet[tokenId][to]=block.timestamp; idtostartingtimet[tokenId][from]=0; 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(ancientnft.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ // function _beforeTokenTransfer( // address from, // address to, // uint256 tokenId // ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: Contracts/nft.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, Ownable, IERC721Enumerable { using Address for address; using Strings for uint256; using Counters for Counters.Counter; // Token name string private _name; // Token symbol string private _symbol; // uint public totalSupply; Counters.Counter private _tokenIds; string public baseURI_ = "ipfs://QmeWdrqHA32zQRjU9oKmsi6NDGdv1dpnyxRi3pcm27Dkqb/"; string public baseExtension = ".json"; uint256 public cost = 0.03 ether; uint256 public maxSupply = 3333; uint256 public maxMintAmount = 10; bool public paused = false; // wallet addresses for claims address private constant possumchsr69 = 0x31FbcD30AA07FBbeA5DB938cD534D1dA79E34985; address private constant Jazzasaurus = 0xd848353706E5a26BAa6DD20265EDDe1e7047d9ba; address private constant munheezy = 0xB6D2ac64BDc24f76417b95b410ACf47cE31AdD07; address private constant _community = 0xe44CB360e48dA69fe75a78fD1649ccbd3CCf7AD1; mapping(uint => mapping(address => uint)) private idtostartingtimet; 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; mapping(address => mapping(uint256 => bool)) private _breeded; ERC20 _ERC20; ancientnft _ancientnft; babynft _babynft; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_,string memory ERC20name_, string memory ERC20symbol_ ,uint ERC20amount,address ERC20owneraddress,string memory ancientnftname_, string memory ancientnftsymbol_,string memory babynftname_, string memory babynftsymbol_) { _name = name_; _symbol = symbol_; mint(msg.sender, 10); _ERC20= new ERC20(ERC20name_,ERC20symbol_,ERC20amount,ERC20owneraddress) ; _ancientnft = new ancientnft(ancientnftname_,ancientnftsymbol_); _ancientnft.setapprovedcontractaddress(address(this)); _ancientnft.seterc20address(address(_ERC20)); _babynft= new babynft(babynftname_,babynftsymbol_); _babynft.setapprovedcontractaddress(address(this)); _babynft.seterc20address(address(_ERC20)); _ERC20.setapprovedcontractaddress(address(this),address(_ancientnft),address(_babynft)); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < 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 < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function pause() public onlyOwner { paused = !paused; } function checkPause() public view onlyOwner returns(bool) { return paused; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { 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); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } 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]; } 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(); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @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())) : ""; } function _baseURI() internal view virtual returns (string memory) { return baseURI_; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; idtostartingtimet[tokenId][to]=block.timestamp; // totalSupply+=1; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; // totalSupply-=1; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } function mint( address _to, uint256 _mintAmount ) public payable { // get total NFT token supply require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require( totalSupply() + _mintAmount <= maxSupply); require(paused == false); // minting is free for first 200 request after which payment is required if ( totalSupply() >= 200) { require(msg.value >= cost * _mintAmount); } // execute mint if (_tokenIds.current()==0){ _tokenIds.increment(); } for (uint256 i = 1; i <= _mintAmount; i++) { uint256 newTokenID = _tokenIds.current(); _safeMint(_to, newTokenID); _tokenIds.increment(); } } function checkdragonnotbreeded(address add)public view returns(uint[] memory){ uint256 ownerTokenCount = balanceOf(add); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(add); uint count; for (uint i ;i<ownerTokenCount; i++){ if (_breeded[address(this)][tokenIds[i]]==false){ count++; } } uint256[] memory notbreededbrtokenIds = new uint256[](count); uint _count; for (uint i ;i<ownerTokenCount; i++){ if (_breeded[address(this)][tokenIds[i]]==false){ notbreededbrtokenIds[_count]=tokenIds[i]; _count++; } } return notbreededbrtokenIds; } function breed(uint id1,uint id2) public { uint amount=1800*10**18; require(balanceOf(msg.sender)>=2, "Must Own 2 0xDragons"); require (_ERC20.balanceOf(msg.sender) >= amount,"You Dont Have The $SCALE For That!"); require (ownerOf(id1)==msg.sender,"NOT YOUR DRAGON"); require (ownerOf(id2)==msg.sender,"NOT YOUR DRAGON"); _ERC20.burn(msg.sender, amount); _breeded[address(this)][id1]=true; _breeded[address(this)][id2]=true; _babynft.mint(msg.sender); } function burn(uint id1, uint id2, uint id3 ) public { uint amount=1500*10**18; require(balanceOf(msg.sender)>=3, "Must Have 3 UNBRED Dragons"); require (_ERC20.balanceOf(msg.sender) >= amount,"You Dont Have The $SCALE For That!"); require (ownerOf(id1)==msg.sender,"NOT YOUR DRAGON"); require (ownerOf(id2)==msg.sender,"NOT YOUR DRAGON"); require (ownerOf(id3)==msg.sender,"NOT YOUR DRAGON"); require( _breeded[address(this)][id1]==false ,"Bred Dragons CAN'T Be Sacrificed"); require( _breeded[address(this)][id2]==false ,"Bred Dragons CAN'T Be Sacrificed"); require( _breeded[address(this)][id3]==false ,"Bred Dragons CAN'T Be Sacrificed"); _ERC20.burn(msg.sender, amount); _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, id1 ); _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, id2 ); _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, id3 ); _ancientnft.mint(msg.sender); } function setmaxsupplyforbabynft(uint amount)public onlyOwner{ _babynft.setmaxsupply(amount); } function setbaseuriforbabynft(string memory _newBaseURI) public onlyOwner{ _babynft.setBaseURI(_newBaseURI); } function setbaseuriforancientnft(string memory _newBaseURI) public onlyOwner{ _ancientnft.setBaseURI(_newBaseURI); } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } // set or update max number of mint per mint call function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI_ = _newBaseURI; } // set metadata base extention function setBaseExtension(string memory _newBaseExtension)public onlyOwner { baseExtension = _newBaseExtension; } function claim() public onlyOwner { // get contract total balance uint256 balance = address(this).balance; // begin withdraw based on address percentage // 40% payable(Jazzasaurus).transfer((balance / 100) * 40); // 20% payable(possumchsr69).transfer((balance / 100) * 20); // 25% payable(munheezy).transfer((balance / 100) * 25); // 15% payable(_community).transfer((balance / 100) * 15); } function walletofNFT(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function checkrewardbal()public view returns(uint){ uint256 ownerTokenCount = balanceOf(msg.sender); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(msg.sender); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][msg.sender]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][msg.sender]; reward = ((10*10**18)*current)/86400; rewardbal+=reward; } } return rewardbal; } function checkrewardforancientbal()public view returns(uint){ return _ancientnft.checkrewardbal(msg.sender); } function checkrewardforbabybal()public view returns(uint){ return _babynft.checkrewardbal(msg.sender); } function claimreward() public { require(balanceOf(msg.sender)>0, "Not Qualified For Reward"); uint256 ownerTokenCount = balanceOf(msg.sender); uint256[] memory tokenIds = new uint256[](ownerTokenCount); tokenIds= walletofNFT(msg.sender); uint current; uint reward; uint rewardbal; for (uint i ;i<ownerTokenCount; i++){ if (idtostartingtimet[tokenIds[i]][msg.sender]>0 ){ current = block.timestamp - idtostartingtimet[tokenIds[i]][msg.sender]; reward = ((10*10**18)*current)/86400; rewardbal+=reward; idtostartingtimet[tokenIds[i]][msg.sender]=block.timestamp; } } _ERC20.mint(msg.sender,rewardbal); if (_ancientnft.balanceOf(msg.sender)>0){ _ancientnft.claimreward(msg.sender); } if (_babynft.balanceOf(msg.sender)>0){ _babynft.claimreward(msg.sender); } } function checkerc20address()public view returns(address) { return (address(_ERC20)); // this is the deployed address of erc20token } function checkancientnftaddress()public view returns(address) { return (address(_ancientnft)); // this is the deployed address of ancienttoken } function checkbabynftaddress()public view returns(address) { return (address(_babynft)); // this is the deployed address of babytoken } 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; idtostartingtimet[tokenId][to]=block.timestamp; idtostartingtimet[tokenId][from]=0; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} }
set metadata base extention
function setBaseExtension(string memory _newBaseExtension)public onlyOwner { baseExtension = _newBaseExtension; }
5,951,714
./full_match/80001/0x9c91476cF83b38573BF15c3c7a69cb1c8EAA7622/sources/contracts/RoboNounsVRGDA.sol
Set the auction per time unit. Only callable by the owner.
function setPerTimeUnit(int256 _perTimeUnit) external onlyOwner { perTimeUnit = _perTimeUnit; emit AuctionPerTimeUnitUpdated(_perTimeUnit); }
9,457,028
./full_match/43114/0x37A83906a69d6236DBcB4d8257D8f62d1f3BBcD5/sources/contracts/BambooStrategyForLP.sol
Allows exit from Staking Contract without additional logic Reward tokens are not automatically collected New deposits will be effectively disabled/
function emergencyWithdraw() external onlyOwner { stakingContract.emergencyWithdraw(PID); totalDeposits = 0; }
4,536,117
./full_match/80001/0x72e9fEc623b2A57f430cDD109b1653997440E3FB/sources/project_/contracts/WeatherFeed.sol
The fulfill method from requests created by this contract The recordChainlinkFulfillment protects this function from being called by anyone other than the oracle address that the request was sent to _requestId The ID that was generated for the request _data The answer provided by the oracle/ weather = bytes32ToString(_data);
function fulfill(bytes32 _requestId, string memory _data) public recordChainlinkFulfillment(_requestId) { weather = _data; }
9,450,032
./partial_match/1/0xE5fEB62FB34aDbA661B7c8256887a8B9a21C2278/sources/contracts/core/utils/ArweaveURILib.sol
Helper function for retrieving a URI stored with {_setURI}. uri The URI storage reference./ Copy `arweaveCID`. First, grab the free memory pointer. Allocate 2 slots. 1 slot for the length, 1 slot for the bytes.
function load(URI storage uri) internal view returns (string memory) { bytes32 arweaveCID = uri.arweave; if (arweaveCID == bytes32(0)) { return uri.regular; } bytes memory decoded; assembly { decoded := mload(0x40) mstore(0x40, add(decoded, 0x40)) } }
3,644,527
./full_match/5/0x19C898E64f5ea99f2599a34d86772391AFf0596B/sources/contracts/CrowdFunding.sol
Definición de funciones del contrato se usa _nombreVariable para indicar que es un parámetro de una función en específico se usa memory para las variables de tipo string Si la función se conectará con el frond-end se debe indicar que es public y decir que valor retornara Para saber que esta bien se usa un require
function createCampaign( address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image ) public returns (uint256) { Campaign storage campaign = campaigns[numberOfCampaigns]; require( campaign.deadline < block.timestamp, "The deadline should be a date in the funture." ); campaign.owner = _owner; campaign.title = _title; campaign.description = _description; campaign.target = _target; campaign.deadline = _deadline; campaign.amountCollected = 0; campaign.image = _image; numberOfCampaigns++; return numberOfCampaigns - 1; }
7,062,220
./partial_match/1/0x2E2BD1FDaBE3450c97b6Bd0C168C8639d6728341/sources/ERC1155xyzUpgradeable.sol
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, uint256 nonce ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); uint256[] memory ids = _asSingletonArray(id); uint256[] memory amounts = _asSingletonArray(amount); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); _tokenOwnerBalance[id][to] += amount; _tokenBalance[id] += amount; if (nonce != 0) { latestBlockNumber[to] = nonce; } emit TransferSingle(operator, address(0), to, id, amount); _afterTokenTransfer(operator, address(0), to, ids, amounts, data); _doSafeTransferAcceptanceCheck( operator, address(0), to, id, amount, data ); }
3,690,073
// SPDX-License-Identifier: MIT // Decentralized Ticketing using NFTs - ERC721 Implementation for Proof of Concept Only // Gas Efficiency and Decentralization/Data Storage Tradeoffs Not Optimized // Torrential Labs - 2021 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Raindrops is ERC721URIStorage, Ownable { uint256 private constant precision = 10000; // Variable to use as a base when calculating percents - all percents have to match this variable size uint256 public creatorPercent; // Fee paid to the event fee address from ticket resale - defaults to event creator unless sold uint256 public protocolPercent; // Fee paid to the protocol from ticket resale and event resale uint256 public depositAmount; // Flat fee that the event/ticket creator pays for each ticket - redeemed by the ticket owner when they attend the event uint256 public depositBalance; // Sum total of outstanding ticket deposits uint256 public protocolTreasury; // Sum total of protocol earnings (ticket resale + expired deposits) address public redemptionManager; // Address for automated redemption daemon address public treasuryManager; // Address which can remove funds from the treasury // Array re-work uint256 public totalEvents; uint256 public totalTickets; // Mappings // Events mapping(string => bool) eventNameToExists; // Default value is false - could go away if event 0 doesn't exist mapping(string => string) eventNameToEventDesc; mapping(string => address) eventNameToOwner; // Only the owner can create tickets and list an event for sale mapping(string => uint256) eventNameToNumberTickets; mapping(string => uint256) eventNameToEventDate; mapping(uint256 => string) public eventNumberToEventName; // Tickets mapping(uint256 => string) ticketNumberToEventName; mapping(uint256 => address) ticketNumberToOwner; mapping(uint256 => string) ticketNumberToURI; mapping(uint256 => uint256) ticketNumberToDeposit; mapping(uint256 => uint256) ticketNumberToPrice; mapping(uint256 => bool) ticketNumberToRedeemed; mapping(uint256 => bool) ticketNumberToSale; // Funding mapping(address => uint256) addressToAmountFunded; // Events event eventCreated(string eventName, string description, uint256 eventDate, uint256 numberTickets, uint256 ticketPrice); event ticketRedemption(string eventName, uint256 ticketNumber, address ticketOwner); event depositAmountUpdated(uint256 oldDepositAmount, uint256 newDepositAmount); event resalePercentUpdated(uint256 oldResalePercent, uint256 newResalePercent); event newTicketsForEvent(string eventName, uint256 numberTickets, uint256 ticketPrice); event ticketListed(uint256 ticketNumber, uint256 price); event ticketDelisted(uint256 ticketNumber); event ticketSold(uint256 ticketNumber, address seller, address buyer, uint256 amount, uint256 creatorFees, uint256 protocolFees); event treasuryFundsRemoved(address sender, uint256 amount); // Contract Constructor // Removed from constructor: uint256 _withdrawLimitThreshold, uint16 _withdrawLimit, uint16 _withdrawCooldown constructor(address _treasuryManager, address _redemptionManager, uint256 _depositAmount, uint256 _creatorPercent, uint256 _protocolPercent) ERC721("Raindrops", "DROP") { require(_creatorPercent <= precision && _protocolPercent <= precision); // Set Helper Contract Adresses redemptionManager = _redemptionManager; treasuryManager = _treasuryManager; // Initialize the protocol fees depositAmount = _depositAmount; creatorPercent = _creatorPercent; protocolPercent = _protocolPercent; } // Protocol Interaction Functions // Add funding to contract to pay for ticket deposits function addFunds() external payable returns(uint256 newBalance) { addressToAmountFunded[msg.sender] += msg.value; return addressToAmountFunded[msg.sender]; } // Remove funding from the contract function removeFunds(uint256 amount) external returns(uint256 newBalance) { // Sender must have the funds require(addressToAmountFunded[msg.sender] >= amount, "RE-0"); // Settle the funds payable(msg.sender).transfer(amount); addressToAmountFunded[msg.sender] -= amount; return addressToAmountFunded[msg.sender]; } // Remove funds from the protocol treasury - call only be called by the treasury manager address function removeFundsTreasury(uint256 amount) external returns(uint256 newBalance) { // Require that the call be the treasury manager require(treasuryManager == msg.sender, "RE-1"); // Prevent the removal of more funds than is allowed require(amount <= protocolTreasury, "RE-2"); // Settle the funds payable(msg.sender).transfer(amount); protocolTreasury -= amount; // Emit Event emit treasuryFundsRemoved(msg.sender, amount); return protocolTreasury; } // Create tickets for a new event function createNewEvent(string memory eventName, string memory eventDescription, uint256 eventDate, uint256 numberTickets, uint256 ticketPrice) external { // Require that an event with the same name does not exist require(eventNameToExists[eventName] == false, "RE-3"); // Create a New Event - 0 event does not exist totalEvents += 1; // Update Mappings eventNumberToEventName[totalEvents] = eventName; eventNameToExists[eventName] = true; eventNameToOwner[eventName] = msg.sender; eventNameToEventDesc[eventName] = eventDescription; eventNameToEventDate[eventName] = eventDate; // Create the Tickets addTickets(eventName, numberTickets, ticketPrice); // Emit Event emit eventCreated(eventName, eventDescription, eventDate, numberTickets, ticketPrice); } // Create additional tickets for an event function addTickets(string memory eventName, uint256 numberTickets, uint256 ticketPrice) public { // Require that the sender owns this event and that they can pay for the ticket deposits require(eventNameToOwner[eventName] == msg.sender, "RE-4"); require(addressToAmountFunded[msg.sender] >= numberTickets * depositAmount, "RE-5"); // Track the new ticket deposits depositBalance += numberTickets * depositAmount; // Update the sender's balance addressToAmountFunded[msg.sender] -= numberTickets * depositAmount; // Create Tickets in a Loop for (uint i; i < numberTickets; i++){ // Update ticket number to next free slot - 0 ticket does not exist totalTickets += 1; // Mint the ERC token _safeMint(msg.sender, totalTickets); // Update Mappings ticketNumberToEventName[totalTickets] = eventName; ticketNumberToOwner[totalTickets] = msg.sender; ticketNumberToDeposit[totalTickets] = depositAmount; ticketNumberToPrice[totalTickets] = ticketPrice; ticketNumberToSale[totalTickets] = true; ticketNumberToRedeemed[totalTickets] = false; } // Update Mappings eventNameToNumberTickets[eventName] += numberTickets; // Emit Event emit newTicketsForEvent(eventName, numberTickets, ticketPrice); } // List a ticket as for sale - this allows it to be bought at any time // If the ticket is already listed for sale then this will update the sale price // Sale price is in ETH (gwei) function listTicket(uint256 ticketNumber, uint256 salePrice) external { // Require that the sender be the owner of this ticket / ticket exists require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-6"); // Allow this ticket to be sold and update the price ticketNumberToSale[ticketNumber] = true; ticketNumberToPrice[ticketNumber] = salePrice; // Emit Event emit ticketListed(ticketNumber, salePrice); } // Delists a ticket from sale - prevents purchase of ticket function delistTicket(uint256 ticketNumber) external { // Require that the sender be the owner of this ticket / ticket exists require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-7"); // Diable this ticket from being sold) - price doesn't need to be updated it will be overrided when relisted ticketNumberToSale[ticketNumber] = false; // Emit Event emit ticketDelisted(ticketNumber); } // Buy a ticket that is listed for sale - you will buy the ticket at the list price function buyTicket(uint256 ticketNumber) external { // Set working variables uint256 ticketPrice = ticketNumberToPrice[ticketNumber]; address ticketOwner = ticketNumberToOwner[ticketNumber]; // Require that the ticket is listed for sale - this will also check that the ticket exists since default bool is false require(ticketNumberToSale[ticketNumber] == true, "RE-8"); // Require that the sender has the funds to buy the ticket require(addressToAmountFunded[msg.sender] > ticketPrice, "RE-9"); // Calculate the protocol fee & creator fees uint256 protocolFee = (ticketPrice * protocolPercent) / precision; uint256 creatorFee = (ticketPrice * creatorPercent) / precision; // Calculate the remaining funds which will be sent from the buyer to the sellers account uint256 saleAmount = ticketPrice - protocolFee - creatorFee; // Transfer ownership of the ticket and the NFT _transfer(ticketOwner, msg.sender, ticketNumber); // Settle the funds - buyer and seller addressToAmountFunded[msg.sender] -= ticketPrice; addressToAmountFunded[ticketOwner] += saleAmount; // Settle the fees - creator and protocol address creatorAddress = eventNameToOwner[ticketNumberToEventName[ticketNumber]]; addressToAmountFunded[creatorAddress] += creatorFee; protocolTreasury += protocolFee; // Emit Event emit ticketSold(ticketNumber, ticketOwner, msg.sender, saleAmount, creatorFee, protocolFee); // Update tracking variables - price doesn't need to be updated it will be overrided when relisted ticketNumberToOwner[ticketNumber] = msg.sender; ticketNumberToSale[ticketNumber] = false; } // Only callable by the redemption address - which can be changed by the owner if needed // ** Move expired determination on-chain within the smart contract later ** // For now expiration will be determined by the redemption daemon in the cloud prior to calling this function function redeemTickets(uint256 [] memory ticketNumbers, bool [] memory expired) external { // Limit redemption of tickets to the redemption address only require(msg.sender == redemptionManager, "RE-10"); for (uint i; i < ticketNumbers.length; i++){ redeemTicket(ticketNumbers[i], expired[i]); } } // Internal Functions // ** Move expired determination on-chain within the smart contract later ** // For now expiration will be determined by the redemption daemon in the cloud prior to calling this function function redeemTicket(uint256 ticketNumber, bool expired) internal { // Check that this ticket has not yet been redeemed - there are safety checks in the cloud already so this should not trigger require(ticketNumberToRedeemed[ticketNumber] == false, "RE-11"); // Safety check to make sure more funds aren't given for deposits than availible - this should never trigger require(depositBalance - ticketNumberToDeposit[ticketNumber] >= 0, "RE-12"); if (!expired) { // Pay the ticket deposit to the ticker owner depositBalance -= ticketNumberToDeposit[ticketNumber]; addressToAmountFunded[ticketNumberToOwner[ticketNumber]] += ticketNumberToDeposit[ticketNumber]; // Emit Event emit ticketRedemption(ticketNumberToEventName[ticketNumber], ticketNumber, ticketNumberToOwner[ticketNumber]); } else { // Deposit fee goes to the protocol - ticket was never scanned at event depositBalance -= ticketNumberToDeposit[ticketNumber]; protocolTreasury += ticketNumberToDeposit[ticketNumber]; // Emit Event emit ticketRedemption(ticketNumberToEventName[ticketNumber], ticketNumber, address(this)); } // Set ticket status to redeemed ticketNumberToRedeemed[ticketNumber] = true; } // Setter Functions function setTokenURI(uint256 ticketNumber, string memory _tokenURI) external onlyOwner { _setTokenURI(ticketNumber, _tokenURI); ticketNumberToURI[ticketNumber] = _tokenURI; } function setDepositAmount(uint256 newDepositAmount) external onlyOwner { emit depositAmountUpdated(depositAmount, newDepositAmount); depositAmount = newDepositAmount; } function setProtocolPercent(uint16 newProtocolPercent) external onlyOwner { // Limit upper bound of the protocol percentage to protect against errors require(newProtocolPercent <= 15000, "RE-13"); emit depositAmountUpdated(protocolPercent, newProtocolPercent); protocolPercent = newProtocolPercent; } function setCreatorPercent(uint16 newCreatorPercent) external onlyOwner { // Limit upper bound of the creator percentage to protect against errors require(newCreatorPercent <= 15000, "RE-14"); emit depositAmountUpdated(creatorPercent, newCreatorPercent); creatorPercent = newCreatorPercent; } // Getter Functions function getAccountBalance(address account) external view returns(uint256 balance) { return addressToAmountFunded[account]; } function getTokenURI(uint256 ticketNumber) public view returns(string memory) { return tokenURI(ticketNumber); } // These view functions can be replaced by a subgraph using the event outputted info // Returns all info for an event - byte size ~ .7KB function getEventInfo(string memory eventName) external view returns( string memory name, string memory description, uint256 date, uint256 ticketCount, address owner, bool exists ) { return (eventName, eventNameToEventDesc[eventName], eventNameToEventDate[eventName], eventNameToNumberTickets[eventName], eventNameToOwner[eventName], eventNameToExists[eventName]); } // Returns all info for a ticket - byte size ~ .7KB function getTicketInfo(uint256 ticketNumber) external view returns( string memory eventName, uint256 deposit, uint256 price, string memory uri, address owner, bool forSale, bool redeemed ) { return (ticketNumberToEventName[ticketNumber], ticketNumberToDeposit[ticketNumber], ticketNumberToPrice[ticketNumber], ticketNumberToURI[ticketNumber], ticketNumberToOwner[ticketNumber], ticketNumberToSale[ticketNumber], ticketNumberToRedeemed[ticketNumber]); } }
List a ticket as for sale - this allows it to be bought at any time If the ticket is already listed for sale then this will update the sale price Sale price is in ETH (gwei) Require that the sender be the owner of this ticket / ticket exists Allow this ticket to be sold and update the price Emit Event
function listTicket(uint256 ticketNumber, uint256 salePrice) external { require(ticketNumberToOwner[ticketNumber] == msg.sender, "RE-6"); ticketNumberToSale[ticketNumber] = true; ticketNumberToPrice[ticketNumber] = salePrice; emit ticketListed(ticketNumber, salePrice); }
1,067,681
// Dependency file: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT // pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol // pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol // pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // Dependency file: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol // pragma solidity >=0.6.2; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // Dependency file: @openzeppelin/contracts/math/Math.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // pragma solidity >=0.6.0 <0.8.0; // import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Dependency file: contracts/interfaces/ISetToken.sol // pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ISetToken * @author Set Protocol * * Interface for operating with SetTokens. */ interface ISetToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a SetToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a SetToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // Dependency file: contracts/interfaces/IBasicIssuanceModule.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity >=0.6.10; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ISetToken _setToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ISetToken _setToken, uint256 _quantity, address _to) external; function redeem(ISetToken _token, uint256 _quantity, address _to) external; } // Dependency file: contracts/interfaces/IController.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; interface IController { function addSet(address _setToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isSet(address _setToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity >=0.6.10; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol // pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // Dependency file: contracts/lib/PreciseUnitMath.sol /* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // pragma solidity 0.6.10; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { SignedSafeMath } from "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // Dependency file: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol // pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // Dependency file: external/contracts/UniSushiV2Library.sol // pragma solidity >=0.5.0; // import '/Users/alexsoong/Source/set-protocol/index-coop-contracts/node_modules/@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; library UniSushiV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // fetches and sorts the reserves for a pair function getReserves(address pair, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pair).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // Root file: contracts/exchangeIssuance/ExchangeIssuance.sol /* Copyright 2021 Index Cooperative Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.6.10; // import { Address } from "@openzeppelin/contracts/utils/Address.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { IUniswapV2Factory } from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; // import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; // import { Math } from "@openzeppelin/contracts/math/Math.sol"; // import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; // import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; // import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import { IBasicIssuanceModule } from "contracts/interfaces/IBasicIssuanceModule.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { ISetToken } from "contracts/interfaces/ISetToken.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { PreciseUnitMath } from "contracts/lib/PreciseUnitMath.sol"; // import { UniSushiV2Library } from "external/contracts/UniSushiV2Library.sol"; /** * @title ExchangeIssuance * @author Index Coop * * Contract for issuing and redeeming any SetToken using ETH or an ERC20 as the paying/receiving currency. * All swaps are done using the best price found on Uniswap or Sushiswap. * */ contract ExchangeIssuance is ReentrancyGuard { using Address for address payable; using SafeMath for uint256; using PreciseUnitMath for uint256; using SafeERC20 for IERC20; using SafeERC20 for ISetToken; /* ============ Enums ============ */ enum Exchange { Uniswap, Sushiswap, None } /* ============ Constants ============= */ uint256 constant private MAX_UINT96 = 2**96 - 1; address constant public ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /* ============ State Variables ============ */ address public WETH; IUniswapV2Router02 public uniRouter; IUniswapV2Router02 public sushiRouter; address public immutable uniFactory; address public immutable sushiFactory; IController public immutable setController; IBasicIssuanceModule public immutable basicIssuanceModule; /* ============ Events ============ */ event ExchangeIssue( address indexed _recipient, // The recipient address of the issued SetTokens ISetToken indexed _setToken, // The issued SetToken IERC20 indexed _inputToken, // The address of the input asset(ERC20/ETH) used to issue the SetTokens uint256 _amountInputToken, // The amount of input tokens used for issuance uint256 _amountSetIssued // The amount of SetTokens received by the recipient ); event ExchangeRedeem( address indexed _recipient, // The recipient address which redeemed the SetTokens ISetToken indexed _setToken, // The redeemed SetToken IERC20 indexed _outputToken, // The address of output asset(ERC20/ETH) received by the recipient uint256 _amountSetRedeemed, // The amount of SetTokens redeemed for output tokens uint256 _amountOutputToken // The amount of output tokens received by the recipient ); event Refund( address indexed _recipient, // The recipient address which redeemed the SetTokens uint256 _refundAmount // The amount of ETH redunded to the recipient ); /* ============ Modifiers ============ */ modifier isSetToken(ISetToken _setToken) { require(setController.isSet(address(_setToken)), "ExchangeIssuance: INVALID SET"); _; } /* ============ Constructor ============ */ constructor( address _weth, address _uniFactory, IUniswapV2Router02 _uniRouter, address _sushiFactory, IUniswapV2Router02 _sushiRouter, IController _setController, IBasicIssuanceModule _basicIssuanceModule ) public { uniFactory = _uniFactory; uniRouter = _uniRouter; sushiFactory = _sushiFactory; sushiRouter = _sushiRouter; setController = _setController; basicIssuanceModule = _basicIssuanceModule; WETH = _weth; IERC20(WETH).safeApprove(address(uniRouter), PreciseUnitMath.maxUint256()); IERC20(WETH).safeApprove(address(sushiRouter), PreciseUnitMath.maxUint256()); } /* ============ Public Functions ============ */ /** * Runs all the necessary approval functions required for a given ERC20 token. * This function can be called when a new token is added to a SetToken during a * rebalance. * * @param _token Address of the token which needs approval */ function approveToken(IERC20 _token) public { _safeApprove(_token, address(uniRouter), MAX_UINT96); _safeApprove(_token, address(sushiRouter), MAX_UINT96); _safeApprove(_token, address(basicIssuanceModule), MAX_UINT96); } /* ============ External Functions ============ */ receive() external payable { // required for weth.withdraw() to work properly require(msg.sender == WETH, "ExchangeIssuance: Direct deposits not allowed"); } /** * Runs all the necessary approval functions required for a list of ERC20 tokens. * * @param _tokens Addresses of the tokens which need approval */ function approveTokens(IERC20[] calldata _tokens) external { for (uint256 i = 0; i < _tokens.length; i++) { approveToken(_tokens[i]); } } /** * Runs all the necessary approval functions required before issuing * or redeeming a SetToken. This function need to be called only once before the first time * this smart contract is used on any particular SetToken. * * @param _setToken Address of the SetToken being initialized */ function approveSetToken(ISetToken _setToken) isSetToken(_setToken) external { address[] memory components = _setToken.getComponents(); for (uint256 i = 0; i < components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); approveToken(IERC20(components[i])); } } /** * Issues SetTokens for an exact amount of input ERC20 tokens. * The ERC20 token must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being issued * @param _inputToken Address of input token * @param _amountInput Amount of the input token / ether to spend * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput, uint256 _minSetReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _amountInput); uint256 amountEth = address(_inputToken) == WETH ? _amountInput : _swapTokenForWETH(_inputToken, _amountInput); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, amountEth); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _amountInput, setTokenAmount); return setTokenAmount; } /** * Issues SetTokens for an exact amount of input ether. * * @param _setToken Address of the SetToken to be issued * @param _minSetReceive Minimum amount of SetTokens to receive. Prevents unnecessary slippage. * * @return setTokenAmount Amount of SetTokens issued to the caller */ function issueSetForExactETH( ISetToken _setToken, uint256 _minSetReceive ) isSetToken(_setToken) external payable nonReentrant returns(uint256) { require(msg.value > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 setTokenAmount = _issueSetForExactWETH(_setToken, _minSetReceive, msg.value); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), msg.value, setTokenAmount); return setTokenAmount; } /** * Issues an exact amount of SetTokens for given amount of input ERC20 tokens. * The excess amount of tokens is returned in an equivalent amount of ether. * * @param _setToken Address of the SetToken to be issued * @param _inputToken Address of the input token * @param _amountSetToken Amount of SetTokens to issue * @param _maxAmountInputToken Maximum amount of input tokens to be used to issue SetTokens. The unused * input tokens are returned as ether. * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromToken( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken, uint256 _maxAmountInputToken ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0 && _maxAmountInputToken > 0, "ExchangeIssuance: INVALID INPUTS"); _inputToken.safeTransferFrom(msg.sender, address(this), _maxAmountInputToken); uint256 initETHAmount = address(_inputToken) == WETH ? _maxAmountInputToken : _swapTokenForWETH(_inputToken, _maxAmountInputToken); uint256 amountEthSpent = _issueExactSetFromWETH(_setToken, _amountSetToken, initETHAmount); uint256 amountEthReturn = initETHAmount.sub(amountEthSpent); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, _inputToken, _maxAmountInputToken, _amountSetToken); return amountEthReturn; } /** * Issues an exact amount of SetTokens using a given amount of ether. * The excess ether is returned back. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return amountEthReturn Amount of ether returned to the caller */ function issueExactSetFromETH( ISetToken _setToken, uint256 _amountSetToken ) isSetToken(_setToken) external payable nonReentrant returns (uint256) { require(msg.value > 0 && _amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); IWETH(WETH).deposit{value: msg.value}(); uint256 amountEth = _issueExactSetFromWETH(_setToken, _amountSetToken, msg.value); uint256 amountEthReturn = msg.value.sub(amountEth); if (amountEthReturn > 0) { IWETH(WETH).withdraw(amountEthReturn); (payable(msg.sender)).sendValue(amountEthReturn); } emit Refund(msg.sender, amountEthReturn); emit ExchangeIssue(msg.sender, _setToken, IERC20(ETH_ADDRESS), amountEth, _amountSetToken); return amountEthReturn; } /** * Redeems an exact amount of SetTokens for an ERC20 token. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken being redeemed * @param _outputToken Address of output token * @param _amountSetToken Amount SetTokens to redeem * @param _minOutputReceive Minimum amount of output token to receive * * @return outputAmount Amount of output tokens sent to the caller */ function redeemExactSetForToken( ISetToken _setToken, IERC20 _outputToken, uint256 _amountSetToken, uint256 _minOutputReceive ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); uint256 outputAmount; if (address(_outputToken) == WETH) { require(totalEth > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); outputAmount = _liquidateComponentsForWETH(components, amountComponents, exchanges); } else { (uint256 totalOutput, Exchange outTokenExchange, ) = _getMaxTokenForExactToken(totalEth, address(WETH), address(_outputToken)); require(totalOutput > _minOutputReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 outputEth = _liquidateComponentsForWETH(components, amountComponents, exchanges); outputAmount = _swapExactTokensForTokens(outTokenExchange, WETH, address(_outputToken), outputEth); } _outputToken.safeTransfer(msg.sender, outputAmount); emit ExchangeRedeem(msg.sender, _setToken, _outputToken, _amountSetToken, outputAmount); return outputAmount; } /** * Redeems an exact amount of SetTokens for ETH. * The SetToken must be approved by the sender to this contract. * * @param _setToken Address of the SetToken to be redeemed * @param _amountSetToken Amount of SetTokens to redeem * @param _minEthOut Minimum amount of ETH to receive * * @return amountEthOut Amount of ether sent to the caller */ function redeemExactSetForETH( ISetToken _setToken, uint256 _amountSetToken, uint256 _minEthOut ) isSetToken(_setToken) external nonReentrant returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); ( uint256 totalEth, uint256[] memory amountComponents, Exchange[] memory exchanges ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); require(totalEth > _minEthOut, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); _redeemExactSet(_setToken, _amountSetToken); uint256 amountEthOut = _liquidateComponentsForWETH(components, amountComponents, exchanges); IWETH(WETH).withdraw(amountEthOut); (payable(msg.sender)).sendValue(amountEthOut); emit ExchangeRedeem(msg.sender, _setToken, IERC20(ETH_ADDRESS), _amountSetToken, amountEthOut); return amountEthOut; } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken being issued * @param _amountInput Amount of the input token to spend * @param _inputToken Address of input token. * * @return Estimated amount of SetTokens that will be received */ function getEstimatedIssueSetAmount( ISetToken _setToken, IERC20 _inputToken, uint256 _amountInput ) isSetToken(_setToken) external view returns (uint256) { require(_amountInput > 0, "ExchangeIssuance: INVALID INPUTS"); uint256 amountEth; if (address(_inputToken) != WETH) { // get max amount of WETH for the `_amountInput` amount of input tokens (amountEth, , ) = _getMaxTokenForExactToken(_amountInput, address(_inputToken), WETH); } else { amountEth = _amountInput; } address[] memory components = _setToken.getComponents(); (uint256 setIssueAmount, , ) = _getSetIssueAmountForETH(_setToken, components, amountEth); return setIssueAmount; } /** * Returns the amount of input ERC20 tokens required to issue an exact amount of SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to issue * * @return Amount of tokens needed to issue specified amount of SetTokens */ function getAmountInToIssueExactSet( ISetToken _setToken, IERC20 _inputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns(uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , , , ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); if (address(_inputToken) == WETH) { return totalEth; } (uint256 tokenAmount, , ) = _getMinTokenForExactToken(totalEth, address(_inputToken), address(WETH)); return tokenAmount; } /** * Returns amount of output ERC20 tokens received upon redeeming a given amount of SetToken. * * @param _setToken Address of SetToken to be redeemed * @param _amountSetToken Amount of SetToken to be redeemed * @param _outputToken Address of output token * * @return Estimated amount of ether/erc20 that will be received */ function getAmountOutOnRedeemSet( ISetToken _setToken, address _outputToken, uint256 _amountSetToken ) isSetToken(_setToken) external view returns (uint256) { require(_amountSetToken > 0, "ExchangeIssuance: INVALID INPUTS"); address[] memory components = _setToken.getComponents(); (uint256 totalEth, , ) = _getAmountETHForRedemption(_setToken, components, _amountSetToken); if (_outputToken == WETH) { return totalEth; } // get maximum amount of tokens for totalEth amount of ETH (uint256 tokenAmount, , ) = _getMaxTokenForExactToken(totalEth, WETH, _outputToken); return tokenAmount; } /* ============ Internal Functions ============ */ /** * Sets a max approval limit for an ERC20 token, provided the current allowance * is less than the required allownce. * * @param _token Token to approve * @param _spender Spender address to approve */ function _safeApprove(IERC20 _token, address _spender, uint256 _requiredAllowance) internal { uint256 allowance = _token.allowance(address(this), _spender); if (allowance < _requiredAllowance) { _token.safeIncreaseAllowance(_spender, MAX_UINT96 - allowance); } } /** * Issues SetTokens for an exact amount of input WETH. * * @param _setToken Address of the SetToken being issued * @param _minSetReceive Minimum amount of index to receive * @param _totalEthAmount Total amount of WETH to be used to purchase the SetToken components * * @return setTokenAmount Amount of SetTokens issued */ function _issueSetForExactWETH(ISetToken _setToken, uint256 _minSetReceive, uint256 _totalEthAmount) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges ) = _getSetIssueAmountForETH(_setToken, components, _totalEthAmount); require(setIssueAmount > _minSetReceive, "ExchangeIssuance: INSUFFICIENT_OUTPUT_AMOUNT"); for (uint256 i = 0; i < components.length; i++) { _swapExactTokensForTokens(exchanges[i], WETH, components[i], amountEthIn[i]); } basicIssuanceModule.issue(_setToken, setIssueAmount, msg.sender); return setIssueAmount; } /** * Issues an exact amount of SetTokens using WETH. * Acquires SetToken components at the best price accross uniswap and sushiswap. * Uses the acquired components to issue the SetTokens. * * @param _setToken Address of the SetToken being issued * @param _amountSetToken Amount of SetTokens to be issued * @param _maxEther Max amount of ether that can be used to acquire the SetToken components * * @return totalEth Total amount of ether used to acquire the SetToken components */ function _issueExactSetFromWETH(ISetToken _setToken, uint256 _amountSetToken, uint256 _maxEther) internal returns (uint256) { address[] memory components = _setToken.getComponents(); ( uint256 sumEth, , Exchange[] memory exchanges, uint256[] memory amountComponents, ) = _getAmountETHForIssuance(_setToken, components, _amountSetToken); require(sumEth <= _maxEther, "ExchangeIssuance: INSUFFICIENT_INPUT_AMOUNT"); uint256 totalEth = 0; for (uint256 i = 0; i < components.length; i++) { uint256 amountEth = _swapTokensForExactTokens(exchanges[i], WETH, components[i], amountComponents[i]); totalEth = totalEth.add(amountEth); } basicIssuanceModule.issue(_setToken, _amountSetToken, msg.sender); return totalEth; } /** * Redeems a given amount of SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _amount Amount of SetToken to be redeemed */ function _redeemExactSet(ISetToken _setToken, uint256 _amount) internal returns (uint256) { _setToken.safeTransferFrom(msg.sender, address(this), _amount); basicIssuanceModule.redeem(_setToken, _amount, address(this)); } /** * Liquidates a given list of SetToken components for WETH. * * @param _components An array containing the address of SetToken components * @param _amountComponents An array containing the amount of each SetToken component * @param _exchanges An array containing the exchange on which to liquidate the SetToken component * * @return Total amount of WETH received after liquidating all SetToken components */ function _liquidateComponentsForWETH(address[] memory _components, uint256[] memory _amountComponents, Exchange[] memory _exchanges) internal returns (uint256) { uint256 sumEth = 0; for (uint256 i = 0; i < _components.length; i++) { sumEth = _exchanges[i] == Exchange.None ? sumEth.add(_amountComponents[i]) : sumEth.add(_swapExactTokensForTokens(_exchanges[i], _components[i], WETH, _amountComponents[i])); } return sumEth; } /** * Gets the total amount of ether required for purchasing each component in a SetToken, * to enable the issuance of a given amount of SetTokens. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be issued * * @return sumEth The total amount of Ether reuired to issue the set * @return amountEthIn An array containing the amount of ether to purchase each component of the SetToken * @return exchanges An array containing the exchange on which to perform the purchase * @return amountComponents An array containing the amount of each SetToken component required for issuing the given * amount of SetToken * @return pairAddresses An array containing the pair addresses of ETH/component exchange pool */ function _getAmountETHForIssuance(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns ( uint256 sumEth, uint256[] memory amountEthIn, Exchange[] memory exchanges, uint256[] memory amountComponents, address[] memory pairAddresses ) { sumEth = 0; amountEthIn = new uint256[](_components.length); amountComponents = new uint256[](_components.length); exchanges = new Exchange[](_components.length); pairAddresses = new address[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); // Get minimum amount of ETH to be spent to acquire the required amount of SetToken component uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = uint256(unit).preciseMulCeil(_amountSetToken); (amountEthIn[i], exchanges[i], pairAddresses[i]) = _getMinTokenForExactToken(amountComponents[i], WETH, _components[i]); sumEth = sumEth.add(amountEthIn[i]); } return (sumEth, amountEthIn, exchanges, amountComponents, pairAddresses); } /** * Gets the total amount of ether returned from liquidating each component in a SetToken. * * @param _setToken Address of the SetToken to be redeemed * @param _components An array containing the addresses of the SetToken components * @param _amountSetToken Amount of SetToken to be redeemed * * @return sumEth The total amount of Ether that would be obtained from liquidating the SetTokens * @return amountComponents An array containing the amount of SetToken component to be liquidated * @return exchanges An array containing the exchange on which to liquidate the SetToken components */ function _getAmountETHForRedemption(ISetToken _setToken, address[] memory _components, uint256 _amountSetToken) internal view returns (uint256, uint256[] memory, Exchange[] memory) { uint256 sumEth = 0; uint256 amountEth = 0; uint256[] memory amountComponents = new uint256[](_components.length); Exchange[] memory exchanges = new Exchange[](_components.length); for (uint256 i = 0; i < _components.length; i++) { // Check that the component does not have external positions require( _setToken.getExternalPositionModules(_components[i]).length == 0, "ExchangeIssuance: EXTERNAL_POSITIONS_NOT_ALLOWED" ); uint256 unit = uint256(_setToken.getDefaultPositionRealUnit(_components[i])); amountComponents[i] = unit.preciseMul(_amountSetToken); // get maximum amount of ETH received for a given amount of SetToken component (amountEth, exchanges[i], ) = _getMaxTokenForExactToken(amountComponents[i], _components[i], WETH); sumEth = sumEth.add(amountEth); } return (sumEth, amountComponents, exchanges); } /** * Returns an estimated amount of SetToken that can be issued given an amount of input ERC20 token. * * @param _setToken Address of the SetToken to be issued * @param _components An array containing the addresses of the SetToken components * @param _amountEth Total amount of ether available for the purchase of SetToken components * * @return setIssueAmount The max amount of SetTokens that can be issued * @return amountEthIn An array containing the amount ether required to purchase each SetToken component * @return exchanges An array containing the exchange on which to purchase the SetToken components */ function _getSetIssueAmountForETH(ISetToken _setToken, address[] memory _components, uint256 _amountEth) internal view returns (uint256 setIssueAmount, uint256[] memory amountEthIn, Exchange[] memory exchanges) { uint256 sumEth; uint256[] memory unitAmountEthIn; uint256[] memory unitAmountComponents; address[] memory pairAddresses; ( sumEth, unitAmountEthIn, exchanges, unitAmountComponents, pairAddresses ) = _getAmountETHForIssuance(_setToken, _components, PreciseUnitMath.preciseUnit()); setIssueAmount = PreciseUnitMath.maxUint256(); amountEthIn = new uint256[](_components.length); for (uint256 i = 0; i < _components.length; i++) { amountEthIn[i] = unitAmountEthIn[i].mul(_amountEth).div(sumEth); uint256 amountComponent; if (exchanges[i] == Exchange.None) { amountComponent = amountEthIn[i]; } else { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(pairAddresses[i], WETH, _components[i]); amountComponent = UniSushiV2Library.getAmountOut(amountEthIn[i], reserveIn, reserveOut); } setIssueAmount = Math.min(amountComponent.preciseDiv(unitAmountComponents[i]), setIssueAmount); } return (setIssueAmount, amountEthIn, exchanges); } /** * Swaps a given amount of an ERC20 token for WETH for the best price on Uniswap/Sushiswap. * * @param _token Address of the ERC20 token to be swapped for WETH * @param _amount Amount of ERC20 token to be swapped * * @return Amount of WETH received after the swap */ function _swapTokenForWETH(IERC20 _token, uint256 _amount) internal returns (uint256) { (, Exchange exchange, ) = _getMaxTokenForExactToken(_amount, address(_token), WETH); IUniswapV2Router02 router = _getRouter(exchange); _safeApprove(_token, address(router), _amount); return _swapExactTokensForTokens(exchange, address(_token), WETH, _amount); } /** * Swap exact tokens for another token on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountIn The amount of input token to be spent * * @return The amount of output tokens */ function _swapExactTokensForTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountIn) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountIn; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapExactTokensForTokens(_amountIn, 0, path, address(this), block.timestamp)[1]; } /** * Swap tokens for exact amount of output tokens on a given DEX. * * @param _exchange The exchange on which to peform the swap * @param _tokenIn The address of the input token * @param _tokenOut The address of the output token * @param _amountOut The amount of output token required * * @return The amount of input tokens spent */ function _swapTokensForExactTokens(Exchange _exchange, address _tokenIn, address _tokenOut, uint256 _amountOut) internal returns (uint256) { if (_tokenIn == _tokenOut) { return _amountOut; } address[] memory path = new address[](2); path[0] = _tokenIn; path[1] = _tokenOut; return _getRouter(_exchange).swapTokensForExactTokens(_amountOut, PreciseUnitMath.maxUint256(), path, address(this), block.timestamp)[0]; } /** * Compares the amount of token required for an exact amount of another token across both exchanges, * and returns the min amount. * * @param _amountOut The amount of output token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The min amount of tokenA required across both exchanges * @return The Exchange on which minimum amount of tokenA is required * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMinTokenForExactToken(uint256 _amountOut, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountOut, Exchange.None, ETH_ADDRESS); } uint256 maxIn = PreciseUnitMath.maxUint256() ; uint256 uniTokenIn = maxIn; uint256 sushiTokenIn = maxIn; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if (uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { uniTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if (sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); // Prevent subtraction overflow by making sure pool reserves are greater than swap amount if (reserveOut > _amountOut) { sushiTokenIn = UniSushiV2Library.getAmountIn(_amountOut, reserveIn, reserveOut); } } // Fails if both the values are maxIn require(!(uniTokenIn == maxIn && sushiTokenIn == maxIn), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenIn <= sushiTokenIn) ? (uniTokenIn, Exchange.Uniswap, uniswapPair) : (sushiTokenIn, Exchange.Sushiswap, sushiswapPair); } /** * Compares the amount of token received for an exact amount of another token across both exchanges, * and returns the max amount. * * @param _amountIn The amount of input token * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The max amount of tokens that can be received across both exchanges * @return The Exchange on which maximum amount of token can be received * @return The pair address of the uniswap/sushiswap pool containing _tokenA and _tokenB */ function _getMaxTokenForExactToken(uint256 _amountIn, address _tokenA, address _tokenB) internal view returns (uint256, Exchange, address) { if (_tokenA == _tokenB) { return (_amountIn, Exchange.None, ETH_ADDRESS); } uint256 uniTokenOut = 0; uint256 sushiTokenOut = 0; address uniswapPair = _getPair(uniFactory, _tokenA, _tokenB); if(uniswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(uniswapPair, _tokenA, _tokenB); uniTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } address sushiswapPair = _getPair(sushiFactory, _tokenA, _tokenB); if(sushiswapPair != address(0)) { (uint256 reserveIn, uint256 reserveOut) = UniSushiV2Library.getReserves(sushiswapPair, _tokenA, _tokenB); sushiTokenOut = UniSushiV2Library.getAmountOut(_amountIn, reserveIn, reserveOut); } // Fails if both the values are 0 require(!(uniTokenOut == 0 && sushiTokenOut == 0), "ExchangeIssuance: ILLIQUID_SET_COMPONENT"); return (uniTokenOut >= sushiTokenOut) ? (uniTokenOut, Exchange.Uniswap, uniswapPair) : (sushiTokenOut, Exchange.Sushiswap, sushiswapPair); } /** * Returns the pair address for on a given DEX. * * @param _factory The factory to address * @param _tokenA The address of tokenA * @param _tokenB The address of tokenB * * @return The pair address (Note: address(0) is returned by default if the pair is not available on that DEX) */ function _getPair(address _factory, address _tokenA, address _tokenB) internal view returns (address) { return IUniswapV2Factory(_factory).getPair(_tokenA, _tokenB); } /** * Returns the router address of a given exchange. * * @param _exchange The Exchange whose router address is needed * * @return IUniswapV2Router02 router of the given exchange */ function _getRouter(Exchange _exchange) internal view returns(IUniswapV2Router02) { return (_exchange == Exchange.Uniswap) ? uniRouter : sushiRouter; } }
Dependency file: contracts/interfaces/IBasicIssuanceModule.sol/ pragma solidity >=0.6.10; import { ISetToken } from "contracts/interfaces/ISetToken.sol";
interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ISetToken _setToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ISetToken _setToken, uint256 _quantity, address _to) external; function redeem(ISetToken _token, uint256 _quantity, address _to) external; }
2,571,787
pragma solidity ^0.4.18; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title 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 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) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } /** * @title LandSale * @dev Landsale contract is a timed, refundable crowdsale for land. It has * a tiered increasing price element based on number of land sold per type. * @notice We omit a fallback function to prevent accidental sends to this contract. */ contract LandSale is Ownable { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; uint256 constant public VILLAGE_START_PRICE = 1200000000000000; // 0.0012 ETH uint256 constant public TOWN_START_PRICE = 5000000000000000; // 0.005 ETH uint256 constant public CITY_START_PRICE = 20000000000000000; // 0.02 ETH uint256 constant public VILLAGE_INCREASE_RATE = 500000000000000; // 0.0005 ETH uint256 constant public TOWN_INCREASE_RATE = 2500000000000000; // 0.0025 ETH uint256 constant public CITY_INCREASE_RATE = 12500000000000000; // 0.0125 ETH // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; // minimum amount of funds to be raised in wei uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; // Array of addresses who purchased land via their ethereum address address[] public walletUsers; uint256 public walletUserCount; // Array of users who purchased land via other method (ex. CC) bytes32[] public ccUsers; uint256 public ccUserCount; // Number of each landType sold uint256 public villagesSold; uint256 public townsSold; uint256 public citiesSold; // 0 - Plot // 1 - Village // 2 - Town // 3 - City // user wallet address -> # of land mapping (address => uint256) public addressToNumVillages; mapping (address => uint256) public addressToNumTowns; mapping (address => uint256) public addressToNumCities; // user id hash -> # of land mapping (bytes32 => uint256) public userToNumVillages; mapping (bytes32 => uint256) public userToNumTowns; mapping (bytes32 => uint256) public userToNumCities; bool private paused = false; bool public isFinalized = false; /** * @dev Send events for every purchase. Also send an event when LandSale is complete */ event LandPurchased(address indexed purchaser, uint256 value, uint8 landType, uint256 quantity); event LandPurchasedCC(bytes32 indexed userId, address indexed purchaser, uint8 landType, uint256 quantity); event Finalized(); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime && !paused); _; } /** * @dev Constructor. One-time set up of goal and opening/closing times of landsale */ function LandSale(address _wallet, uint256 _goal, uint256 _openingTime, uint256 _closingTime) public { require(_wallet != address(0)); require(_goal > 0); require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); wallet = _wallet; vault = new RefundVault(wallet); goal = _goal; openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Add new ethereum wallet users to array */ function addWalletAddress(address walletAddress) private { if ((addressToNumVillages[walletAddress] == 0) && (addressToNumTowns[walletAddress] == 0) && (addressToNumCities[walletAddress] == 0)) { // only add address to array during first land purchase walletUsers.push(msg.sender); walletUserCount++; } } /** * @dev Add new CC users to array */ function addCCUser(bytes32 user) private { if ((userToNumVillages[user] == 0) && (userToNumTowns[user] == 0) && (userToNumCities[user] == 0)) { // only add user to array during first land purchase ccUsers.push(user); ccUserCount++; } } /** * @dev Purchase a village. For bulk purchase, current price honored for all * villages purchased. */ function purchaseVillage(uint256 numVillages) payable public onlyWhileOpen { require(msg.value >= (villagePrice()*numVillages)); require(numVillages > 0); weiRaised = weiRaised.add(msg.value); villagesSold = villagesSold.add(numVillages); addWalletAddress(msg.sender); addressToNumVillages[msg.sender] = addressToNumVillages[msg.sender].add(numVillages); _forwardFunds(); LandPurchased(msg.sender, msg.value, 1, numVillages); } /** * @dev Purchase a town. For bulk purchase, current price honored for all * towns purchased. */ function purchaseTown(uint256 numTowns) payable public onlyWhileOpen { require(msg.value >= (townPrice()*numTowns)); require(numTowns > 0); weiRaised = weiRaised.add(msg.value); townsSold = townsSold.add(numTowns); addWalletAddress(msg.sender); addressToNumTowns[msg.sender] = addressToNumTowns[msg.sender].add(numTowns); _forwardFunds(); LandPurchased(msg.sender, msg.value, 2, numTowns); } /** * @dev Purchase a city. For bulk purchase, current price honored for all * cities purchased. */ function purchaseCity(uint256 numCities) payable public onlyWhileOpen { require(msg.value >= (cityPrice()*numCities)); require(numCities > 0); weiRaised = weiRaised.add(msg.value); citiesSold = citiesSold.add(numCities); addWalletAddress(msg.sender); addressToNumCities[msg.sender] = addressToNumCities[msg.sender].add(numCities); _forwardFunds(); LandPurchased(msg.sender, msg.value, 3, numCities); } /** * @dev Accounting for the CC purchases for audit purposes (no actual ETH transfer here) */ function purchaseLandWithCC(uint8 landType, bytes32 userId, uint256 num) public onlyOwner onlyWhileOpen { require(landType <= 3); require(num > 0); addCCUser(userId); if (landType == 3) { weiRaised = weiRaised.add(cityPrice()*num); citiesSold = citiesSold.add(num); userToNumCities[userId] = userToNumCities[userId].add(num); } else if (landType == 2) { weiRaised = weiRaised.add(townPrice()*num); townsSold = townsSold.add(num); userToNumTowns[userId] = userToNumTowns[userId].add(num); } else if (landType == 1) { weiRaised = weiRaised.add(villagePrice()*num); villagesSold = villagesSold.add(num); userToNumVillages[userId] = userToNumVillages[userId].add(num); } LandPurchasedCC(userId, msg.sender, landType, num); } /** * @dev Returns the current price of a village. Price raises every 10 purchases. */ function villagePrice() view public returns(uint256) { return VILLAGE_START_PRICE.add((villagesSold.div(10).mul(VILLAGE_INCREASE_RATE))); } /** * @dev Returns the current price of a town. Price raises every 10 purchases */ function townPrice() view public returns(uint256) { return TOWN_START_PRICE.add((townsSold.div(10).mul(TOWN_INCREASE_RATE))); } /** * @dev Returns the current price of a city. Price raises every 10 purchases */ function cityPrice() view public returns(uint256) { return CITY_START_PRICE.add((citiesSold.div(10).mul(CITY_INCREASE_RATE))); } /** * @dev Allows owner to pause puchases during the landsale */ function pause() onlyOwner public { paused = true; } /** * @dev Allows owner to resume puchases during the landsale */ function resume() onlyOwner public { paused = false; } /** * @dev Allows owner to check the paused status * @return Whether landsale is paused */ function isPaused () onlyOwner public view returns(bool) { return paused; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } Finalized(); isFinalized = true; } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } }
Constructor. One-time set up of goal and opening/closing times of landsale/
function LandSale(address _wallet, uint256 _goal, uint256 _openingTime, uint256 _closingTime) public { require(_wallet != address(0)); require(_goal > 0); require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); wallet = _wallet; vault = new RefundVault(wallet); goal = _goal; openingTime = _openingTime; closingTime = _closingTime; }
14,035,129
pragma solidity ^0.4.24; // File: @0xcert/ethereum-utils/contracts/math/SafeMath.sol /** * @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-erc721/contracts/tokens/ERC721Enumerable.sol /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Enumerable { /** * @dev Returns 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); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It 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)`. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721.sol /** * @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-erc721/contracts/tokens/ERC721TokenReceiver.sol /** * @dev ERC-721 interface for accepting safe transfers. See https://goo.gl/pc9yoS. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. 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. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @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. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) external returns(bytes4); } // File: @0xcert/ethereum-utils/contracts/utils/AddressUtils.sol /** * @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: @0xcert/ethereum-utils/contracts/utils/ERC165.sol /** * @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/utils/SupportsInterface.sol /** * @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-erc721/contracts/tokens/NFToken.sol /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApprovals; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) internal ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; /** * @dev Magic value of a smart contract that can recieve NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @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. * @param _from Sender of NFT (if address is zero address it indicates token creation). * @param _to Receiver of NFT (if address is zero address it indicates token destruction). * @param _tokenId The NFT that got transfered. */ 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. * @param _owner Owner of NFT. * @param _approved Address that we are approving. * @param _tokenId NFT which we are approving. */ 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. * @param _owner Owner of NFT. * @param _operator Address to which we are setting operator rights. * @param _approved Status of operator rights(true if operator rights are given and false if * revoked). */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender]); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || getApproved(_tokenId) == msg.sender || ownerToOperators[tokenOwner][msg.sender] ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0)); _; } /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @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) { require(_owner != address(0)); return ownerToNFTokenCount[_owner]; } /** * @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 _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0)); } /** * @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 { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @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 { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @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 maybe 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 canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); } /** * @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 Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner); idToApprovals[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @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 This works even if sender doesn't own any tokens at the time. * @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 { require(_operator != address(0)); ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. */ function getApproved( uint256 _tokenId ) public view validNFToken(_tokenId) returns (address) { return idToApprovals[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @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) { require(_owner != address(0)); require(_operator != address(0)); return ownerToOperators[_owner][_operator]; } /** * @dev Actually perform the safeTransferFrom. * @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 ) internal canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from); require(_to != address(0)); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED); } } /** * @dev Actually preforms the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) private { address from = idToOwner[_tokenId]; clearApproval(_tokenId); removeNFToken(from, _tokenId); addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is a private function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal { require(_to != address(0)); require(_tokenId != 0); require(idToOwner[_tokenId] == address(0)); addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is a private function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) validNFToken(_tokenId) internal { clearApproval(_tokenId); removeNFToken(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function clearApproval( uint256 _tokenId ) private { if(idToApprovals[_tokenId] != 0) { delete idToApprovals[_tokenId]; } } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function removeNFToken( address _from, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == _from); assert(ownerToNFTokenCount[_from] > 0); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from].sub(1); delete idToOwner[_tokenId]; } /** * @dev Assignes a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function addNFToken( address _to, uint256 _tokenId ) internal { require(idToOwner[_tokenId] == address(0)); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].add(1); } } // File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenEnumerable.sol /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Mints a new NFT. * @notice This is a private function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length.sub(1); } /** * @dev Burns a NFT. * @notice This is a private function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) internal { super._burn(_owner, _tokenId); assert(tokens.length > 0); uint256 tokenIndex = idToIndex[_tokenId]; // Sanity check. This could be removed in the future. assert(tokens[tokenIndex] == _tokenId); uint256 lastTokenIndex = tokens.length.sub(1); uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.length--; // Consider adding a conditional check for the last token in order to save GAS. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function removeNFToken( address _from, uint256 _tokenId ) internal { super.removeNFToken(_from, _tokenId); assert(ownerToIds[_from].length > 0); uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length.sub(1); uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; ownerToIds[_from].length--; // Consider adding a conditional check for the last token in order to save GAS. idToOwnerIndex[lastToken] = tokenToRemoveIndex; idToOwnerIndex[_tokenId] = 0; } /** * @dev Assignes a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function addNFToken( address _to, uint256 _tokenId ) internal { super.addNFToken(_to, _tokenId); uint256 length = ownerToIds[_to].length; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = length; } /** * @dev Returns the count of all existing NFTokens. */ function totalSupply() external view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. */ function tokenByIndex( uint256 _index ) external view returns (uint256) { require(_index < tokens.length); // Sanity check. This could be removed in the future. assert(idToIndex[tokens[_index]] == _index); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256) { require(_index < ownerToIds[_owner].length); return ownerToIds[_owner][_index]; } } // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721Metadata.sol /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://goo.gl/pc9yoS. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. */ function name() external view returns (string _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. */ function symbol() external view returns (string _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". */ function tokenURI(uint256 _tokenId) external view returns (string); } // File: @0xcert/ethereum-erc721/contracts/tokens/NFTokenMetadata.sol /** * @dev Optional metadata implementation for ERC-721 non-fungible token standard. */ contract NFTokenMetadata is NFToken, ERC721Metadata { /** * @dev A descriptive name for a collection of NFTs. */ string internal nftName; /** * @dev An abbreviated name for NFTokens. */ string internal nftSymbol; /** * @dev Mapping from NFT ID to metadata uri. */ mapping (uint256 => string) internal idToUri; /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftName and nftSymbol. */ constructor() public { supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } /** * @dev Burns a NFT. * @notice This is a internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _owner Address of the NFT owner. * @param _tokenId ID of the NFT to be burned. */ function _burn( address _owner, uint256 _tokenId ) internal { super._burn(_owner, _tokenId); if (bytes(idToUri[_tokenId]).length != 0) { delete idToUri[_tokenId]; } } /** * @dev Set a distinct URI (RFC 3986) for a given NFT ID. * @notice this is a internal function which should be called from user-implemented external * function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _tokenId Id for which we want uri. * @param _uri String representing RFC 3986 URI. */ function _setTokenUri( uint256 _tokenId, string _uri ) validNFToken(_tokenId) internal { idToUri[_tokenId] = _uri; } /** * @dev Returns a descriptive name for a collection of NFTokens. */ function name() external view returns (string _name) { _name = nftName; } /** * @dev Returns an abbreviated name for NFTokens. */ function symbol() external view returns (string _symbol) { _symbol = nftSymbol; } /** * @dev A distinct URI (RFC 3986) for a given NFT. * @param _tokenId Id for which we want uri. */ function tokenURI( uint256 _tokenId ) validNFToken(_tokenId) external view returns (string) { return idToUri[_tokenId]; } } // File: @0xcert/ethereum-utils/contracts/ownership/Ownable.sol /** * @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-xcert/contracts/tokens/Xcert.sol /** * @dev Xcert implementation. */ contract Xcert is NFTokenEnumerable, NFTokenMetadata, Ownable { using SafeMath for uint256; using AddressUtils for address; /** * @dev Unique ID which determines each Xcert smart contract type by its JSON convention. * @notice Calculated as bytes4(keccak256(jsonSchema)). */ bytes4 internal nftConventionId; /** * @dev Maps NFT ID to proof. */ mapping (uint256 => string) internal idToProof; /** * @dev Maps NFT ID to protocol config. */ mapping (uint256 => bytes32[]) internal config; /** * @dev Maps NFT ID to convention data. */ mapping (uint256 => bytes32[]) internal data; /** * @dev Maps address to authorization of contract. */ mapping (address => bool) internal addressToAuthorized; /** * @dev Emits when an address is authorized to some contract control or the authorization is revoked. * The _target has some contract controle like minting new NFTs. * @param _target Address to set authorized state. * @param _authorized True if the _target is authorised, false to revoke authorization. */ event AuthorizedAddress( address indexed _target, bool _authorized ); /** * @dev Guarantees that msg.sender is allowed to mint a new NFT. */ modifier isAuthorized() { require(msg.sender == owner || addressToAuthorized[msg.sender]); _; } /** * @dev Contract constructor. * @notice When implementing this contract don't forget to set nftConventionId, nftName and * nftSymbol. */ constructor() public { supportedInterfaces[0x6be14f75] = true; // Xcert } /** * @dev Mints a new NFT. * @param _to The address that will own the minted NFT. * @param _id The NFT to be minted by the msg.sender. * @param _uri An URI pointing to NFT metadata. * @param _proof Cryptographic asset imprint. * @param _config Array of protocol config values where 0 index represents token expiration * timestamp, other indexes are not yet definied but are ready for future xcert upgrades. * @param _data Array of convention data values. */ function mint( address _to, uint256 _id, string _uri, string _proof, bytes32[] _config, bytes32[] _data ) external isAuthorized() { require(_config.length > 0); require(bytes(_proof).length > 0); super._mint(_to, _id); super._setTokenUri(_id, _uri); idToProof[_id] = _proof; config[_id] = _config; data[_id] = _data; } /** * @dev Returns a bytes4 of keccak256 of json schema representing 0xcert protocol convention. */ function conventionId() external view returns (bytes4 _conventionId) { _conventionId = nftConventionId; } /** * @dev Returns proof for NFT. * @param _tokenId Id of the NFT. */ function tokenProof( uint256 _tokenId ) validNFToken(_tokenId) external view returns(string) { return idToProof[_tokenId]; } /** * @dev Returns convention data value for a given index field. * @param _tokenId Id of the NFT we want to get value for key. * @param _index for which we want to get value. */ function tokenDataValue( uint256 _tokenId, uint256 _index ) validNFToken(_tokenId) public view returns(bytes32 value) { require(_index < data[_tokenId].length); value = data[_tokenId][_index]; } /** * @dev Returns expiration date from 0 index of token config values. * @param _tokenId Id of the NFT we want to get expiration time of. */ function tokenExpirationTime( uint256 _tokenId ) validNFToken(_tokenId) external view returns(bytes32) { return config[_tokenId][0]; } /** * @dev Sets authorised address for minting. * @param _target Address to set authorized state. * @param _authorized True if the _target is authorised, false to revoke authorization. */ function setAuthorizedAddress( address _target, bool _authorized ) onlyOwner external { require(_target != address(0)); addressToAuthorized[_target] = _authorized; emit AuthorizedAddress(_target, _authorized); } /** * @dev Sets mint authorised address. * @param _target Address for which we want to check if it is authorized. * @return Is authorized or not. */ function isAuthorizedAddress( address _target ) external view returns (bool) { require(_target != address(0)); return addressToAuthorized[_target]; } } // File: @0xcert/ethereum-erc20/contracts/tokens/ERC20.sol /** * @title A standard interface for tokens. */ interface ERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string _name); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string _symbol); /** * @dev Returns the number of decimals the token uses. */ function decimals() external view returns (uint8 _decimals); /** * @dev Returns the total token supply. */ function totalSupply() external view returns (uint256 _totalSupply); /** * @dev Returns the account balance of another account with address _owner. * @param _owner The address from which the balance will be retrieved. */ function balanceOf( address _owner ) external view returns (uint256 _balance); /** * @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transfer( address _to, uint256 _value ) external returns (bool _success); /** * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the * Transfer event. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) external returns (bool _success); /** * @dev Allows _spender to withdraw from your account multiple times, up to * the _value amount. If this function is called again it overwrites the current * allowance with _value. * @param _spender The address of the account able to transfer the tokens. * @param _value The amount of tokens to be approved for transfer. */ function approve( address _spender, uint256 _value ) external returns (bool _success); /** * @dev Returns the amount which _spender is still allowed to withdraw from _owner. * @param _owner The address of the account owning tokens. * @param _spender The address of the account able to transfer the tokens. */ function allowance( address _owner, address _spender ) external view returns (uint256 _remaining); /** * @dev Triggers when tokens are transferred, including zero value transfers. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Triggers on any successful call to approve(address _spender, uint256 _value). */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); } // File: @0xcert/ethereum-erc20/contracts/tokens/Token.sol /** * @title ERC20 standard token implementation. * @dev Standard ERC20 token. This contract follows the implementation at https://goo.gl/mLbAPJ. */ contract Token is ERC20 { using SafeMath for uint256; /** * Token name. */ string internal tokenName; /** * Token symbol. */ string internal tokenSymbol; /** * Number of decimals. */ uint8 internal tokenDecimals; /** * Total supply of tokens. */ uint256 internal tokenTotalSupply; /** * Balance information map. */ mapping (address => uint256) internal balances; /** * Token allowance mapping. */ mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Trigger when tokens are transferred, including zero value transfers. */ event Transfer( address indexed _from, address indexed _to, uint256 _value ); /** * @dev Trigger on any successful call to approve(address _spender, uint256 _value). */ event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /** * @dev Returns the name of the token. */ function name() external view returns (string _name) { _name = tokenName; } /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string _symbol) { _symbol = tokenSymbol; } /** * @dev Returns the number of decimals the token uses. */ function decimals() external view returns (uint8 _decimals) { _decimals = tokenDecimals; } /** * @dev Returns the total token supply. */ function totalSupply() external view returns (uint256 _totalSupply) { _totalSupply = tokenTotalSupply; } /** * @dev Returns the account balance of another account with address _owner. * @param _owner The address from which the balance will be retrieved. */ function balanceOf( address _owner ) external view returns (uint256 _balance) { _balance = balances[_owner]; } /** * @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The * function SHOULD throw if the _from account balance does not have enough tokens to spend. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transfer( address _to, uint256 _value ) public returns (bool _success) { require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _success = true; } /** * @dev Allows _spender to withdraw from your account multiple times, up to the _value amount. If * this function is called again it overwrites the current allowance with _value. * @param _spender The address of the account able to transfer the tokens. * @param _value The amount of tokens to be approved for transfer. */ function approve( address _spender, uint256 _value ) public returns (bool _success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); _success = true; } /** * @dev Returns the amount which _spender is still allowed to withdraw from _owner. * @param _owner The address of the account owning tokens. * @param _spender The address of the account able to transfer the tokens. */ function allowance( address _owner, address _spender ) external view returns (uint256 _remaining) { _remaining = allowed[_owner][_spender]; } /** * @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the * Transfer event. * @param _from The address of the sender. * @param _to The address of the recipient. * @param _value The amount of token to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool _success) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); _success = true; } } // File: @0xcert/ethereum-zxc/contracts/tokens/Zxc.sol /* * @title ZXC protocol token. * @dev Standard ERC20 token used by the 0xcert protocol. This contract follows the implementation * at https://goo.gl/twbPwp. */ contract Zxc is Token, Ownable { using SafeMath for uint256; /** * Transfer feature state. */ bool internal transferEnabled; /** * Crowdsale smart contract address. */ address public crowdsaleAddress; /** * @dev An event which is triggered when tokens are burned. * @param _burner The address which burns tokens. * @param _value The amount of burned tokens. */ event Burn( address indexed _burner, uint256 _value ); /** * @dev Assures that the provided address is a valid destination to transfer tokens to. * @param _to Target address. */ modifier validDestination( address _to ) { require(_to != address(0x0)); require(_to != address(this)); require(_to != address(crowdsaleAddress)); _; } /** * @dev Assures that tokens can be transfered. */ modifier onlyWhenTransferAllowed() { require(transferEnabled || msg.sender == crowdsaleAddress); _; } /** * @dev Contract constructor. */ constructor() public { tokenName = "0xcert Protocol Token"; tokenSymbol = "ZXC"; tokenDecimals = 18; tokenTotalSupply = 400000000000000000000000000; transferEnabled = false; balances[owner] = tokenTotalSupply; emit Transfer(address(0x0), owner, tokenTotalSupply); } /** * @dev Transfers 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 ) onlyWhenTransferAllowed() validDestination(_to) public returns (bool _success) { _success = super.transfer(_to, _value); } /** * @dev Transfers 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 ) onlyWhenTransferAllowed() validDestination(_to) public returns (bool _success) { _success = super.transferFrom(_from, _to, _value); } /** * @dev Enables token transfers. */ function enableTransfer() onlyOwner() external { transferEnabled = true; } /** * @dev Burns a specific amount of tokens. This function is based on BurnableToken implementation * at goo.gl/GZEhaq. * @notice Only owner is allowed to perform this operation. * @param _value The amount of tokens to be burned. */ function burn( uint256 _value ) onlyOwner() external { require(_value <= balances[msg.sender]); balances[owner] = balances[owner].sub(_value); tokenTotalSupply = tokenTotalSupply.sub(_value); emit Burn(owner, _value); emit Transfer(owner, address(0x0), _value); } /** * @dev Set crowdsale address which can distribute tokens even when onlyWhenTransferAllowed is * false. * @param crowdsaleAddr Address of token offering contract. */ function setCrowdsaleAddress( address crowdsaleAddr ) external onlyOwner() { crowdsaleAddress = crowdsaleAddr; } } // File: contracts/crowdsale/ZxcCrowdsale.sol /** * @title ZXC crowdsale contract. * @dev Crowdsale contract for distributing ZXC tokens. * Start timestamps for the token sale stages (start dates are inclusive, end exclusive): * - Token presale with 10% bonus: 2018/06/26 - 2018/07/04 * - Token sale with 5% bonus: 2018/07/04 - 2018/07/05 * - Token sale with 0% bonus: 2018/07/05 - 2018/07/18 */ contract ZxcCrowdsale { using SafeMath for uint256; /** * @dev Token being sold. */ Zxc public token; /** * @dev Xcert KYC token. */ Xcert public xcertKyc; /** * @dev Start time of the presale. */ uint256 public startTimePresale; /** * @dev Start time of the token sale with bonus. */ uint256 public startTimeSaleWithBonus; /** * @dev Start time of the token sale with no bonus. */ uint256 public startTimeSaleNoBonus; /** * @dev Presale bonus expressed as percentage integer (10% = 10). */ uint256 public bonusPresale; /** * @dev Token sale bonus expressed as percentage integer (10% = 10). */ uint256 public bonusSale; /** * @dev End timestamp to end the crowdsale. */ uint256 public endTime; /** * @dev Minimum required wei deposit for public presale period. */ uint256 public minimumPresaleWeiDeposit; /** * @dev Total amount of ZXC tokens offered for the presale. */ uint256 public preSaleZxcCap; /** * @dev Total supply of ZXC tokens for the sale. */ uint256 public crowdSaleZxcSupply; /** * @dev Amount of ZXC tokens sold. */ uint256 public zxcSold; /** * @dev Address where funds are collected. */ address public wallet; /** * @dev How many token units buyer gets per wei. */ uint256 public rate; /** * @dev An event which is triggered when tokens are bought. * @param _from The address sending tokens. * @param _to The address receiving tokens. * @param _weiAmount Purchase amount in wei. * @param _tokenAmount The amount of purchased tokens. */ event TokenPurchase( address indexed _from, address indexed _to, uint256 _weiAmount, uint256 _tokenAmount ); /** * @dev Contract constructor. * @param _walletAddress Address of the wallet which collects funds. * @param _tokenAddress Address of the ZXC token contract. * @param _xcertKycAddress Address of the Xcert KYC token contract. * @param _startTimePresale Start time of presale stage. * @param _startTimeSaleWithBonus Start time of public sale stage with bonus. * @param _startTimeSaleNoBonus Start time of public sale stage with no bonus. * @param _endTime Time when sale ends. * @param _rate ZXC/ETH exchange rate. * @param _presaleZxcCap Maximum number of ZXC offered for the presale. * @param _crowdSaleZxcSupply Supply of ZXC tokens offered for the sale. Includes _presaleZxcCap. * @param _bonusPresale Bonus token percentage for presale. * @param _bonusSale Bonus token percentage for public sale stage with bonus. * @param _minimumPresaleWeiDeposit Minimum required deposit in wei. */ constructor( address _walletAddress, address _tokenAddress, address _xcertKycAddress, uint256 _startTimePresale, // 1529971200: date -d '2018-06-26 00:00:00 UTC' +%s uint256 _startTimeSaleWithBonus, // 1530662400: date -d '2018-07-04 00:00:00 UTC' +%s uint256 _startTimeSaleNoBonus, //1530748800: date -d '2018-07-05 00:00:00 UTC' +%s uint256 _endTime, // 1531872000: date -d '2018-07-18 00:00:00 UTC' +%s uint256 _rate, // 10000: 1 ETH = 10,000 ZXC uint256 _presaleZxcCap, // 195M uint256 _crowdSaleZxcSupply, // 250M uint256 _bonusPresale, // 10 (%) uint256 _bonusSale, // 5 (%) uint256 _minimumPresaleWeiDeposit // 1 ether; ) public { require(_walletAddress != address(0)); require(_tokenAddress != address(0)); require(_xcertKycAddress != address(0)); require(_tokenAddress != _walletAddress); require(_tokenAddress != _xcertKycAddress); require(_xcertKycAddress != _walletAddress); token = Zxc(_tokenAddress); xcertKyc = Xcert(_xcertKycAddress); uint8 _tokenDecimals = token.decimals(); require(_tokenDecimals == 18); // Sanity check. wallet = _walletAddress; // Bonus should be > 0% and <= 100% require(_bonusPresale > 0 && _bonusPresale <= 100); require(_bonusSale > 0 && _bonusSale <= 100); bonusPresale = _bonusPresale; bonusSale = _bonusSale; require(_startTimeSaleWithBonus > _startTimePresale); require(_startTimeSaleNoBonus > _startTimeSaleWithBonus); startTimePresale = _startTimePresale; startTimeSaleWithBonus = _startTimeSaleWithBonus; startTimeSaleNoBonus = _startTimeSaleNoBonus; endTime = _endTime; require(_rate > 0); rate = _rate; require(_crowdSaleZxcSupply > 0); require(token.totalSupply() >= _crowdSaleZxcSupply); crowdSaleZxcSupply = _crowdSaleZxcSupply; require(_presaleZxcCap > 0 && _presaleZxcCap <= _crowdSaleZxcSupply); preSaleZxcCap = _presaleZxcCap; zxcSold = 71157402800000000000000000; require(_minimumPresaleWeiDeposit > 0); minimumPresaleWeiDeposit = _minimumPresaleWeiDeposit; } /** * @dev Fallback function can be used to buy tokens. */ function() external payable { buyTokens(); } /** * @dev Low level token purchase function. */ function buyTokens() public payable { uint256 tokens; // Sender needs Xcert KYC token. uint256 balance = xcertKyc.balanceOf(msg.sender); require(balance > 0); uint256 tokenId = xcertKyc.tokenOfOwnerByIndex(msg.sender, balance - 1); uint256 kycLevel = uint(xcertKyc.tokenDataValue(tokenId, 0)); if (isInTimeRange(startTimePresale, startTimeSaleWithBonus)) { require(kycLevel > 1); require(msg.value >= minimumPresaleWeiDeposit); tokens = getTokenAmount(msg.value, bonusPresale); require(zxcSold.add(tokens) <= preSaleZxcCap); } else if (isInTimeRange(startTimeSaleWithBonus, startTimeSaleNoBonus)) { require(kycLevel > 0); tokens = getTokenAmount(msg.value, bonusSale); } else if (isInTimeRange(startTimeSaleNoBonus, endTime)) { require(kycLevel > 0); tokens = getTokenAmount(msg.value, uint256(0)); } else { revert("Purchase outside of token sale time windows"); } require(zxcSold.add(tokens) <= crowdSaleZxcSupply); zxcSold = zxcSold.add(tokens); wallet.transfer(msg.value); require(token.transferFrom(token.owner(), msg.sender, tokens)); emit TokenPurchase(msg.sender, msg.sender, msg.value, tokens); } /** * @return true if crowdsale event has ended */ function hasEnded() external view returns (bool) { bool capReached = zxcSold >= crowdSaleZxcSupply; bool endTimeReached = now >= endTime; return capReached || endTimeReached; } /** * @dev Check if currently active period is a given time period. * @param _startTime Starting timestamp (inclusive). * @param _endTime Ending timestamp (exclusive). * @return bool */ function isInTimeRange( uint256 _startTime, uint256 _endTime ) internal view returns(bool) { if (now >= _startTime && now < _endTime) { return true; } else { return false; } } /** * @dev Calculate amount of tokens for a given wei amount. Apply special bonuses depending on * @param weiAmount Amount of wei for token purchase. * @param bonusPercent Percentage of bonus tokens. * @return Number of tokens with possible bonus. */ function getTokenAmount( uint256 weiAmount, uint256 bonusPercent ) internal view returns(uint256) { uint256 tokens = weiAmount.mul(rate); if (bonusPercent > 0) { uint256 bonusTokens = tokens.mul(bonusPercent).div(uint256(100)); // tokens * bonus (%) / 100% tokens = tokens.add(bonusTokens); } return tokens; } }
Transfers token to a specified address. _to The address to transfer to. _value The amount to be transferred./
function transfer( address _to, uint256 _value ) onlyWhenTransferAllowed() validDestination(_to) public returns (bool _success) { _success = super.transfer(_to, _value); }
5,546,337
./partial_match/42/0xA2903a37FB83FFcbD3B91B0495015e50D34e0b85/sources/Jackpot.sol
Calculates user dividends stakeSharesParam Param from stake to calculate bonuses for beginDay First day to calculate bonuses for endDay Last day (non-inclusive) of range to calculate bonuses for return Payout in Suns/
function calcPayoutDividendsReward( uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) public view returns (uint256 payout) { uint256 currDay = _currentDay(); require(beginDay < currDay, "JACKPOT: Wrong argument for beginDay"); require(endDay <= currDay && beginDay <= endDay, "JACKPOT: Wrong argument for endDay"); require(globals.latestStakeId != 0, "JACKPOT: latestStakeId error."); uint256 day = beginDay; while(day < endDay && day < globals.dailyDataCount) { uint256 dayPayout; dayPayout += ((dailyData[day].dayDividends * 90) / 100) * stakeSharesParam / dailyData[day].dayStakeSharesTotal; payout += dayPayout; day++; uint256 dayStakeSharesTotal = dailyData[globals.dailyDataCount - 1].dayStakeSharesTotal; require(dayStakeSharesTotal != 0, "JACKPOT: dayStakeSharesTotal == 0"); while(day < endDay) { uint256 dayPayout; dayPayout += ((xfLobby[day] * 90) / 100) * stakeSharesParam / dayStakeSharesTotal; payout += dayPayout; day++; return payout; }
8,897,688
./partial_match/1/0x41A028f0B8C83C4D02bbEA9497ea6092271b1ced/sources/NyanVoting.sol
Public function that allows anyone to execute the current top bid./
function executeBid() public _updateState(msg.sender) { if (!isAdmin[msg.sender]) { require(currentVotingEndBlock < block.number, "Voting period is still active."); } currentVotingStartBlock = block.number + 10; currentVotingEndBlock = currentVotingStartBlock.add(votingPeriodBlockLength); NConnector connectorContract = NConnector(connectorAddress); NFund fundContract = NFund(fundAddress); if (isTopBid) { if (!isAdmin[msg.sender]) { require(currentBids[topBidAddress].votes >= requiredVoteCount, "The top bid needs more votes"); } connectorContract.executeBid( currentBids[topBidAddress].functionCode, currentBids[topBidAddress].functionName, currentBids[topBidAddress].addresses, currentBids[topBidAddress].integers, currentBids[topBidAddress].strings, currentBids[topBidAddress].bytesArr ); for (uint256 c = 0; c<currentBids[topBidAddress].chain.length; c++) { connectorContract.executeBid( bidChains[currentBids[topBidAddress].chain[c]].functionCode, bidChains[currentBids[topBidAddress].chain[c]].functionName, bidChains[currentBids[topBidAddress].chain[c]].addresses, bidChains[currentBids[topBidAddress].chain[c]].integers, bidChains[currentBids[topBidAddress].chain[c]].strings, bidChains[currentBids[topBidAddress].chain[c]].bytesArr); } } delete proposals; topBidAddress = address(0); topBidVotes = 0; isTopBid = false; emit BidExecution(currentBids[topBidAddress].bidder, currentBids[topBidAddress].bidId); }
3,580,453
// SPDX-License-Identifier: Apache-2.0 // Copyright 2017 Loopring Technology Limited. pragma solidity ^0.7.0; contract Ownable { address public owner; event OWNERSHIPTRANSFERRED745( //inject NONSTANDARD NAMING address indexed previousOwner, address indexed newOwner ); constructor() { owner = msg.sender; } modifier ONLYOWNER112() //inject NONSTANDARD NAMING { require(msg.sender == owner, "UNAUTHORIZED"); _; } function TRANSFEROWNERSHIP715( //inject NONSTANDARD NAMING address newOwner ) public virtual ONLYOWNER112 { require(newOwner != address(0), "ZERO_ADDRESS"); emit OWNERSHIPTRANSFERRED745(owner, newOwner); owner = newOwner; } function RENOUNCEOWNERSHIP221() //inject NONSTANDARD NAMING public ONLYOWNER112 { emit OWNERSHIPTRANSFERRED745(owner, address(0)); owner = address(0); } } // Copyright 2017 Loopring Technology Limited. contract Claimable is Ownable { address public pendingOwner; modifier ONLYPENDINGOWNER834() { //inject NONSTANDARD NAMING require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } function TRANSFEROWNERSHIP715( //inject NONSTANDARD NAMING address newOwner ) public override ONLYOWNER112 { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } function CLAIMOWNERSHIP503() //inject NONSTANDARD NAMING public ONLYPENDINGOWNER834 { emit OWNERSHIPTRANSFERRED745(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // Copyright 2017 Loopring Technology Limited. library MathUint { using MathUint for uint; function MUL260( //inject NONSTANDARD NAMING uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function SUB429( //inject NONSTANDARD NAMING uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function ADD886( //inject NONSTANDARD NAMING uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function ADD64567( //inject NONSTANDARD NAMING uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. library AddressUtil { using AddressUtil for *; function ISCONTRACT780( //inject NONSTANDARD NAMING address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function TOPAYABLE290( //inject NONSTANDARD NAMING address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function SENDETH93( //inject NONSTANDARD NAMING address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.TOPAYABLE290(); (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function SENDETHANDVERIFY115( //inject NONSTANDARD NAMING address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.SENDETH93(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function FASTCALL566( //inject NONSTANDARD NAMING address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function FASTCALLANDVERIFY742( //inject NONSTANDARD NAMING address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = FASTCALL566(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // Copyright 2017 Loopring Technology Limited. library ERC20SafeTransfer { function SAFETRANSFERANDVERIFY454( //inject NONSTANDARD NAMING address token, address to, uint value ) internal { SAFETRANSFERWITHGASLIMITANDVERIFY643( token, to, value, gasleft() ); } function SAFETRANSFER263( //inject NONSTANDARD NAMING address token, address to, uint value ) internal returns (bool) { return SAFETRANSFERWITHGASLIMIT116( token, to, value, gasleft() ); } function SAFETRANSFERWITHGASLIMITANDVERIFY643( //inject NONSTANDARD NAMING address token, address to, uint value, uint gasLimit ) internal { require( SAFETRANSFERWITHGASLIMIT116(token, to, value, gasLimit), "TRANSFER_FAILURE" ); } function SAFETRANSFERWITHGASLIMIT116( //inject NONSTANDARD NAMING address token, address to, uint value, uint gasLimit ) internal returns (bool) { // A transfer is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb bytes memory callData = abi.encodeWithSelector( bytes4(0xa9059cbb), to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return CHECKRETURNVALUE539(success); } function SAFETRANSFERFROMANDVERIFY218( //inject NONSTANDARD NAMING address token, address from, address to, uint value ) internal { SAFETRANSFERFROMWITHGASLIMITANDVERIFY78( token, from, to, value, gasleft() ); } function SAFETRANSFERFROM863( //inject NONSTANDARD NAMING address token, address from, address to, uint value ) internal returns (bool) { return SAFETRANSFERFROMWITHGASLIMIT242( token, from, to, value, gasleft() ); } function SAFETRANSFERFROMWITHGASLIMITANDVERIFY78( //inject NONSTANDARD NAMING address token, address from, address to, uint value, uint gasLimit ) internal { bool result = SAFETRANSFERFROMWITHGASLIMIT242( token, from, to, value, gasLimit ); require(result, "TRANSFER_FAILURE"); } function SAFETRANSFERFROMWITHGASLIMIT242( //inject NONSTANDARD NAMING address token, address from, address to, uint value, uint gasLimit ) internal returns (bool) { // A transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return CHECKRETURNVALUE539(success); } function CHECKRETURNVALUE539( //inject NONSTANDARD NAMING bool success ) internal pure returns (bool) { // A transfer/transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) if (success) { assembly { switch returndatasize() // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded case 0 { success := 1 } // Standard ERC20: a single boolean value is returned which needs to be true case 32 { returndatacopy(0, 0, 32) success := mload(0) } // None of the above: not successful default { success := 0 } } } return success; } } // Copyright 2017 Loopring Technology Limited. contract ReentrancyGuard { //The default value must be 0 in order to work behind a proxy. uint private _guardValue; // Use this modifier on a function to prevent reentrancy modifier NONREENTRANT948() //inject NONSTANDARD NAMING { // Check if the guard value has its original value require(_guardValue == 0, "REENTRANCY"); // Set the value to something else _guardValue = 1; // Function body _; // Set the value back _guardValue = 0; } } // Copyright 2017 Loopring Technology Limited. pragma experimental ABIEncoderV2; // Copyright 2017 Loopring Technology Limited. // Copyright 2017 Loopring Technology Limited. interface IAgent{} interface IAgentRegistry { function ISAGENT707( //inject NONSTANDARD NAMING address owner, address agent ) external view returns (bool); function ISAGENT707( //inject NONSTANDARD NAMING address[] calldata owners, address agent ) external view returns (bool); } // Copyright 2017 Loopring Technology Limited. abstract contract IBlockVerifier is Claimable { // -- Events -- event CIRCUITREGISTERED31( //inject NONSTANDARD NAMING uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CIRCUITDISABLED690( //inject NONSTANDARD NAMING uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- function REGISTERCIRCUIT284( //inject NONSTANDARD NAMING uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; function DISABLECIRCUIT787( //inject NONSTANDARD NAMING uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; function VERIFYPROOFS612( //inject NONSTANDARD NAMING uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); function ISCIRCUITREGISTERED877( //inject NONSTANDARD NAMING uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); function ISCIRCUITENABLED480( //inject NONSTANDARD NAMING uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // Copyright 2017 Loopring Technology Limited. /// interface IDepositContract { function ISTOKENSUPPORTED796(address token) //inject NONSTANDARD NAMING external view returns (bool); /// /// /// function DEPOSIT812( //inject NONSTANDARD NAMING address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// /// /// function WITHDRAW961( //inject NONSTANDARD NAMING address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// /// /// function TRANSFER658( //inject NONSTANDARD NAMING address from, address to, address token, uint amount ) external payable; /// /// function ISETH195(address addr) //inject NONSTANDARD NAMING external view returns (bool); } library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. AuxiliaryData[] auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } function SNARK_SCALAR_FIELD483() internal pure returns (uint) { //inject NONSTANDARD NAMING // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. return 21888242871839275222246405745257275088548364400416034343698204186575808495617; } function MAX_OPEN_FORCED_REQUESTS307() internal pure returns (uint16) { return 4096; } //inject NONSTANDARD NAMING function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE249() internal pure returns (uint32) { return 15 days; } //inject NONSTANDARD NAMING function TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS626() internal pure returns (uint32) { return 7 days; } //inject NONSTANDARD NAMING function MAX_NUM_ACCOUNTS339() internal pure returns (uint) { return 2 ** 32; } //inject NONSTANDARD NAMING function MAX_NUM_TOKENS337() internal pure returns (uint) { return 2 ** 16; } //inject NONSTANDARD NAMING function MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED702() internal pure returns (uint32) { return 7 days; } //inject NONSTANDARD NAMING function MIN_TIME_IN_SHUTDOWN3() internal pure returns (uint32) { return 30 days; } //inject NONSTANDARD NAMING // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. function TX_DATA_AVAILABILITY_SIZE508() internal pure returns (uint32) { return 68; } //inject NONSTANDARD NAMING function MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND638() internal pure returns (uint32) { return 15 days; } //inject NONSTANDARD NAMING function ACCOUNTID_PROTOCOLFEE156() internal pure returns (uint32) { return 0; } //inject NONSTANDARD NAMING function TX_DATA_AVAILABILITY_SIZE_PART_1259() internal pure returns (uint32) { return 29; } //inject NONSTANDARD NAMING function TX_DATA_AVAILABILITY_SIZE_PART_2833() internal pure returns (uint32) { return 39; } //inject NONSTANDARD NAMING struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint96 weightAMM; uint storageRoot; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; } } /// /// abstract contract IExchangeV3 is Claimable { // -- Events -- event EXCHANGECLONED511( //inject NONSTANDARD NAMING address exchangeAddress, address owner, bytes32 genesisMerkleRoot ); event TOKENREGISTERED650( //inject NONSTANDARD NAMING address token, uint16 tokenId ); event SHUTDOWN33( //inject NONSTANDARD NAMING uint timestamp ); event WITHDRAWALMODEACTIVATED651( //inject NONSTANDARD NAMING uint timestamp ); event BLOCKSUBMITTED428( //inject NONSTANDARD NAMING uint indexed blockIdx, bytes32 merkleRoot, bytes32 publicDataHash ); event DEPOSITREQUESTED482( //inject NONSTANDARD NAMING address from, address to, address token, uint16 tokenId, uint96 amount ); event FORCEDWITHDRAWALREQUESTED509( //inject NONSTANDARD NAMING address owner, address token, uint32 accountID ); event WITHDRAWALCOMPLETED711( //inject NONSTANDARD NAMING uint8 category, address from, address to, address token, uint amount ); event WITHDRAWALFAILED876( //inject NONSTANDARD NAMING uint8 category, address from, address to, address token, uint amount ); event PROTOCOLFEESUPDATED599( //inject NONSTANDARD NAMING uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); event TRANSACTIONAPPROVED992( //inject NONSTANDARD NAMING address owner, bytes32 transactionHash ); // events from libraries // -- Initialization -- function INITIALIZE599( //inject NONSTANDARD NAMING address loopring, address owner, bytes32 genesisMerkleRoot ) virtual external; function SETAGENTREGISTRY336(address agentRegistry) //inject NONSTANDARD NAMING external virtual; function GETAGENTREGISTRY130() //inject NONSTANDARD NAMING external virtual view returns (IAgentRegistry); function SETDEPOSITCONTRACT329(address depositContract) //inject NONSTANDARD NAMING external virtual; function GETDEPOSITCONTRACT552() //inject NONSTANDARD NAMING external virtual view returns (IDepositContract); // @dev Exchange owner withdraws fees from the exchange. // @param token Fee token address // @param feeRecipient Fee recipient address function WITHDRAWEXCHANGEFEES258( //inject NONSTANDARD NAMING address token, address feeRecipient ) external virtual; // -- Constants -- function GETCONSTANTS860() //inject NONSTANDARD NAMING external virtual pure returns(ExchangeData.Constants memory); // -- Mode -- function ISINWITHDRAWALMODE735() //inject NONSTANDARD NAMING external virtual view returns (bool); function ISSHUTDOWN18() //inject NONSTANDARD NAMING external virtual view returns (bool); // -- Tokens -- /// /// /// function REGISTERTOKEN777( //inject NONSTANDARD NAMING address tokenAddress ) external virtual returns (uint16 tokenID); function GETTOKENID492( //inject NONSTANDARD NAMING address tokenAddress ) external virtual view returns (uint16 tokenID); function GETTOKENADDRESS957( //inject NONSTANDARD NAMING uint16 tokenID ) external virtual view returns (address tokenAddress); // -- Stakes -- /// function GETEXCHANGESTAKE420() //inject NONSTANDARD NAMING external virtual view returns (uint); /// /// function WITHDRAWEXCHANGESTAKE391( //inject NONSTANDARD NAMING address recipient ) external virtual returns (uint amountLRC); /// function BURNEXCHANGESTAKE0() //inject NONSTANDARD NAMING external virtual; // -- Blocks -- function GETMERKLEROOT398() //inject NONSTANDARD NAMING external virtual view returns (bytes32); function GETBLOCKHEIGHT308() //inject NONSTANDARD NAMING external virtual view returns (uint); function GETBLOCKINFO928(uint blockIdx) //inject NONSTANDARD NAMING external virtual view returns (ExchangeData.BlockInfo memory); /// /// function SUBMITBLOCKS846(ExchangeData.Block[] calldata blocks) //inject NONSTANDARD NAMING external virtual; function GETNUMAVAILABLEFORCEDSLOTS361() //inject NONSTANDARD NAMING external virtual view returns (uint); // -- Deposits -- /// /// /// function DEPOSIT812( //inject NONSTANDARD NAMING address from, address to, address tokenAddress, uint96 amount, bytes calldata auxiliaryData ) external virtual payable; function GETPENDINGDEPOSITAMOUNT893( //inject NONSTANDARD NAMING address owner, address tokenAddress ) external virtual view returns (uint96); // -- Withdrawals -- /// /// /// /// function FORCEWITHDRAW720( //inject NONSTANDARD NAMING address owner, address tokenAddress, uint32 accountID ) external virtual payable; function ISFORCEDWITHDRAWALPENDING612( //inject NONSTANDARD NAMING uint32 accountID, address token ) external virtual view returns (bool); /// /// /// function WITHDRAWPROTOCOLFEES774( //inject NONSTANDARD NAMING address tokenAddress ) external virtual payable; function GETPROTOCOLFEELASTWITHDRAWNTIME313( //inject NONSTANDARD NAMING address tokenAddress ) external virtual view returns (uint); /// /// /// function WITHDRAWFROMMERKLETREE611( //inject NONSTANDARD NAMING ExchangeData.MerkleProof calldata merkleProof ) external virtual; function ISWITHDRAWNINWITHDRAWALMODE951( //inject NONSTANDARD NAMING uint32 accountID, address token ) external virtual view returns (bool); /// /// function WITHDRAWFROMDEPOSITREQUEST842( //inject NONSTANDARD NAMING address owner, address token ) external virtual; /// /// /// /// function WITHDRAWFROMAPPROVEDWITHDRAWALS239( //inject NONSTANDARD NAMING address[] calldata owners, address[] calldata tokens ) external virtual; function GETAMOUNTWITHDRAWABLE280( //inject NONSTANDARD NAMING address owner, address token ) external virtual view returns (uint); /// /// function NOTIFYFORCEDREQUESTTOOOLD650( //inject NONSTANDARD NAMING uint32 accountID, address token ) external virtual; /// /// function SETWITHDRAWALRECIPIENT592( //inject NONSTANDARD NAMING address from, address to, address token, uint96 amount, uint32 storageID, address newRecipient ) external virtual; /// function GETWITHDRAWALRECIPIENT486( //inject NONSTANDARD NAMING address from, address to, address token, uint96 amount, uint32 storageID ) external virtual view returns (address); /// /// function ONCHAINTRANSFERFROM491( //inject NONSTANDARD NAMING address from, address to, address token, uint amount ) external virtual; /// /// function APPROVETRANSACTION417( //inject NONSTANDARD NAMING address owner, bytes32 txHash ) external virtual; /// /// function APPROVETRANSACTIONS714( //inject NONSTANDARD NAMING address[] calldata owners, bytes32[] calldata txHashes ) external virtual; /// function ISTRANSACTIONAPPROVED916( //inject NONSTANDARD NAMING address owner, bytes32 txHash ) external virtual view returns (bool); // -- Admins -- function SETMAXAGEDEPOSITUNTILWITHDRAWABLE624( //inject NONSTANDARD NAMING uint32 newValue ) external virtual returns (uint32); function GETMAXAGEDEPOSITUNTILWITHDRAWABLE693() //inject NONSTANDARD NAMING external virtual view returns (uint32); /// /// /// function SHUTDOWN305() //inject NONSTANDARD NAMING external virtual returns (bool success); function GETPROTOCOLFEEVALUES606() //inject NONSTANDARD NAMING external virtual view returns ( uint32 syncedAt, uint8 takerFeeBips, uint8 makerFeeBips, uint8 previousTakerFeeBips, uint8 previousMakerFeeBips ); function GETDOMAINSEPARATOR671() //inject NONSTANDARD NAMING external virtual view returns (bytes32); } // Copyright 2017 Loopring Technology Limited. abstract contract ILoopringV3 is Claimable { // == Events == event EXCHANGESTAKEDEPOSITED907(address exchangeAddr, uint amount); //inject NONSTANDARD NAMING event EXCHANGESTAKEWITHDRAWN386(address exchangeAddr, uint amount); //inject NONSTANDARD NAMING event EXCHANGESTAKEBURNED415(address exchangeAddr, uint amount); //inject NONSTANDARD NAMING event SETTINGSUPDATED90(uint time); //inject NONSTANDARD NAMING // == Public Variables == mapping (address => uint) internal exchangeStake; address public lrcAddress; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// function UPDATESETTINGS249( //inject NONSTANDARD NAMING address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// function UPDATEPROTOCOLFEESETTINGS464( //inject NONSTANDARD NAMING uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; function GETEXCHANGESTAKE420( //inject NONSTANDARD NAMING address exchangeAddr ) public virtual view returns (uint stakedLRC); function BURNEXCHANGESTAKE0( //inject NONSTANDARD NAMING uint amount ) external virtual returns (uint burnedLRC); function DEPOSITEXCHANGESTAKE519( //inject NONSTANDARD NAMING address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); function WITHDRAWEXCHANGESTAKE391( //inject NONSTANDARD NAMING address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); function GETPROTOCOLFEEVALUES606( //inject NONSTANDARD NAMING ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } contract LoopringV3 is ILoopringV3, ReentrancyGuard { using AddressUtil for address payable; using MathUint for uint; using ERC20SafeTransfer for address; // -- Constructor -- constructor( address _lrcAddress, address payable _protocolFeeVault, address _blockVerifierAddress ) Claimable() { require(address(0) != _lrcAddress, "ZERO_ADDRESS"); lrcAddress = _lrcAddress; UPDATESETTINGSINTERNAL160(_protocolFeeVault, _blockVerifierAddress, 0); } // == Public Functions == function UPDATESETTINGS249( //inject NONSTANDARD NAMING address payable _protocolFeeVault, address _blockVerifierAddress, uint _forcedWithdrawalFee ) external override NONREENTRANT948 ONLYOWNER112 { UPDATESETTINGSINTERNAL160( _protocolFeeVault, _blockVerifierAddress, _forcedWithdrawalFee ); } function UPDATEPROTOCOLFEESETTINGS464( //inject NONSTANDARD NAMING uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external override NONREENTRANT948 ONLYOWNER112 { protocolTakerFeeBips = _protocolTakerFeeBips; protocolMakerFeeBips = _protocolMakerFeeBips; emit SETTINGSUPDATED90(block.timestamp); } function GETEXCHANGESTAKE420( //inject NONSTANDARD NAMING address exchangeAddr ) public override view returns (uint) { return exchangeStake[exchangeAddr]; } function BURNEXCHANGESTAKE0( //inject NONSTANDARD NAMING uint amount ) external override NONREENTRANT948 returns (uint burnedLRC) { burnedLRC = exchangeStake[msg.sender]; if (amount < burnedLRC) { burnedLRC = amount; } if (burnedLRC > 0) { lrcAddress.SAFETRANSFERANDVERIFY454(protocolFeeVault, burnedLRC); exchangeStake[msg.sender] = exchangeStake[msg.sender].SUB429(burnedLRC); totalStake = totalStake.SUB429(burnedLRC); } emit EXCHANGESTAKEBURNED415(msg.sender, burnedLRC); } function DEPOSITEXCHANGESTAKE519( //inject NONSTANDARD NAMING address exchangeAddr, uint amountLRC ) external override NONREENTRANT948 returns (uint stakedLRC) { require(amountLRC > 0, "ZERO_VALUE"); lrcAddress.SAFETRANSFERFROMANDVERIFY218(msg.sender, address(this), amountLRC); stakedLRC = exchangeStake[exchangeAddr].ADD886(amountLRC); exchangeStake[exchangeAddr] = stakedLRC; totalStake = totalStake.ADD886(amountLRC); emit EXCHANGESTAKEDEPOSITED907(exchangeAddr, amountLRC); } function WITHDRAWEXCHANGESTAKE391( //inject NONSTANDARD NAMING address recipient, uint requestedAmount ) external override NONREENTRANT948 returns (uint amountLRC) { uint stake = exchangeStake[msg.sender]; amountLRC = (stake > requestedAmount) ? requestedAmount : stake; if (amountLRC > 0) { lrcAddress.SAFETRANSFERANDVERIFY454(recipient, amountLRC); exchangeStake[msg.sender] = exchangeStake[msg.sender].SUB429(amountLRC); totalStake = totalStake.SUB429(amountLRC); } emit EXCHANGESTAKEWITHDRAWN386(msg.sender, amountLRC); } function GETPROTOCOLFEEVALUES606() //inject NONSTANDARD NAMING public override view returns ( uint8 takerFeeBips, uint8 makerFeeBips ) { return (protocolTakerFeeBips, protocolMakerFeeBips); } // == Internal Functions == function UPDATESETTINGSINTERNAL160( //inject NONSTANDARD NAMING address payable _protocolFeeVault, address _blockVerifierAddress, uint _forcedWithdrawalFee ) private { require(address(0) != _protocolFeeVault, "ZERO_ADDRESS"); require(address(0) != _blockVerifierAddress, "ZERO_ADDRESS"); protocolFeeVault = _protocolFeeVault; blockVerifierAddress = _blockVerifierAddress; forcedWithdrawalFee = _forcedWithdrawalFee; emit SETTINGSUPDATED90(block.timestamp); } }
inject NONSTANDARD NAMING
function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE249() internal pure returns (uint32) { return 15 days; }
5,458,522
pragma solidity ^0.4.24; /*-------------------------------------------------- ____ ____ _ / ___| _ _ _ __ ___ _ __ / ___|__ _ _ __ __| | \___ \| | | | '_ \ / _ \ '__| | | / _` | '__/ _` | ___) | |_| | |_) | __/ | | |__| (_| | | | (_| | |____/ \__,_| .__/ \___|_| \____\__,_|_| \__,_| |_| 2018-08-08 V0.8 ---------------------------------------------------*/ contract SPCevents { // 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 P3DAmount, 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 P3DAmount, uint256 genAmount ); // 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 P3DAmount, uint256 genAmount ); // 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 P3DAmount, 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, add pot directly by admin to next round event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract SuperCard is SPCevents { using SafeMath for *; using NameFilter for string; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xbac825cdb506dcf917a7715a4bf3fa1b06abe3e4); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; string constant public name = "SuperCard"; string constant public symbol = "SPC"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 6 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 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_; // last rID uint256 public pID_; // last pID //**************** // 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 => SPCdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => SPCdatasets.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 => SPCdatasets.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 mapping (uint256 => uint256) public attend; // (index => pID) player ID attend current round //**************** // TEAM FEE DATA //**************** mapping (uint256 => SPCdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => SPCdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { fees_[0] = SPCdatasets.TeamFee(80,2); fees_[1] = SPCdatasets.TeamFee(80,2); fees_[2] = SPCdatasets.TeamFee(80,2); fees_[3] = SPCdatasets.TeamFee(80,2); // how to split up the final pot based on which team was picked potSplit_[0] = SPCdatasets.PotSplit(20,10); potSplit_[1] = SPCdatasets.PotSplit(20,10); potSplit_[2] = SPCdatasets.PotSplit(20,10); potSplit_[3] = SPCdatasets.PotSplit(20,10); /* activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; */ } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { if ( activated_ == false ){ if ( (now >= pre_active_time) && (pre_active_time > 0) ){ activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } require(activated_ == true, "its not ready yet."); _; } /** * @dev prevents contracts from interacting with SuperCard */ 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 SPCdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _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 SPCdatasets.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; } // buy core, team set to 2, snake buyCore(_pID, _affCode, 2, _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 SPCdatasets.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; } } // buy core, team set to 2, snake buyCore(_pID, _affID, 2, _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 SPCdatasets.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; } } // buy core, team set to 2, snake buyCore(_pID, _affID, 2, _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 SPCdatasets.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; } // reload core, team set to 2, snake reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data SPCdatasets.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; } } // reload core, team set to 2, snake reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data SPCdatasets.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; } } // reload core, team set to 2, snake reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 upperLimit = 0; uint256 usedGen = 0; // eth send to player uint256 ethout = 0; uint256 over_gen = 0; updateGenVault(_pID, plyr_[_pID].lrnd); if (plyr_[_pID].gen > 0) { upperLimit = (calceth(plyrRnds_[_pID][rID_].keys).mul(105))/100; if(plyr_[_pID].gen >= upperLimit) { over_gen = (plyr_[_pID].gen).sub(upperLimit); round_[rID_].keys = (round_[rID_].keys).sub(plyrRnds_[_pID][rID_].keys); plyrRnds_[_pID][rID_].keys = 0; round_[rID_].pot = (round_[rID_].pot).add(over_gen); usedGen = upperLimit; } else { plyrRnds_[_pID][rID_].keys = (plyrRnds_[_pID][rID_].keys).sub(calckeys(((plyr_[_pID].gen).mul(100))/105)); round_[rID_].keys = (round_[rID_].keys).sub(calckeys(((plyr_[_pID].gen).mul(100))/105)); usedGen = plyr_[_pID].gen; } ethout = ((plyr_[_pID].win).add(plyr_[_pID].aff)).add(usedGen); } else { ethout = ((plyr_[_pID].win).add(plyr_[_pID].aff)); } plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; plyr_[_pID].addr.transfer(ethout); // 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 SPCdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[rID_].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit SPCevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, ethout, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // fire withdraw event emit SPCevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, ethout, _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 SPCevents.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 SPCevents.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 SPCevents.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) { // price 0.01 ETH return(10000000000000000); } /** * @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) return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } /** * @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 whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls 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, 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 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @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, SPCdatasets.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, 2, _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 SPCevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault, to win vault plyr_[_pID].win = plyr_[_pID].win.add(msg.value); } } /** * @dev gen limit handle */ function genLimit(uint256 _pID) private returns(uint256) { uint256 upperLimit = 0; uint256 usedGen = 0; uint256 over_gen = 0; uint256 eth_can_use = 0; uint256 tempnum = 0; updateGenVault(_pID, plyr_[_pID].lrnd); if (plyr_[_pID].gen > 0) { upperLimit = ((plyrRnds_[_pID][rID_].keys).mul(105))/10000; if(plyr_[_pID].gen >= upperLimit) { over_gen = (plyr_[_pID].gen).sub(upperLimit); round_[rID_].keys = (round_[rID_].keys).sub(plyrRnds_[_pID][rID_].keys); plyrRnds_[_pID][rID_].keys = 0; round_[rID_].pot = (round_[rID_].pot).add(over_gen); usedGen = upperLimit; } else { tempnum = ((plyr_[_pID].gen).mul(10000))/105; plyrRnds_[_pID][rID_].keys = (plyrRnds_[_pID][rID_].keys).sub(tempnum); round_[rID_].keys = (round_[rID_].keys).sub(tempnum); usedGen = plyr_[_pID].gen; } eth_can_use = ((plyr_[_pID].win).add(plyr_[_pID].aff)).add(usedGen); plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } else { eth_can_use = (plyr_[_pID].win).add(plyr_[_pID].aff); plyr_[_pID].win = 0; plyr_[_pID].aff = 0; } return(eth_can_use); } /** * @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 _eth, SPCdatasets.EventReturns memory _eventData_) private { // setup local rID // grab time uint256 _now = now; uint256 eth_can_use = 0; // 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. eth_can_use = genLimit(_pID); if(eth_can_use > 0) { // call core core(rID_, _pID, eth_can_use, _affID, 2, _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 SPCevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _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, SPCdatasets.EventReturns memory _eventData_) private { // if player is new to round。 if (plyrRnds_[_pID][_rID].jionflag != 1) { _eventData_ = managePlayer(_pID, _eventData_); plyrRnds_[_pID][_rID].jionflag = 1; attend[round_[_rID].attendNum] = _pID; round_[_rID].attendNum = (round_[_rID].attendNum).add(1); } if (_eth > 10000000000000000) { // mint the new keys uint256 _keys = calckeys(_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; round_[_rID].team = 2; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // 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][2] = _eth.add(rndTmEth_[_rID][2]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, 2, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, 2, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, 2, _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) { uint256 temp; temp = (round_[_rIDlast].mask).mul((plyrRnds_[_pID][_rIDlast].keys)/1000000000000000000); if(temp > plyrRnds_[_pID][_rIDlast].mask) { return( temp.sub(plyrRnds_[_pID][_rIDlast].mask) ); } else { return( 0 ); } } /** * @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) { return ( calckeys(_eth) ); } /** * @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) { return ( _keys/100 ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @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(SPCdatasets.EventReturns memory _eventData_) private returns (SPCdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of SuperCard if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); pID_ = _pID; // save Last pID 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 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, SPCdatasets.EventReturns memory _eventData_) private returns (SPCdatasets.EventReturns) { uint256 temp_eth = 0; // if player has played a previous round, move their unmasked earnings // from that round to win vault. if (plyr_[_pID].lrnd != 0) { updateGenVault(_pID, plyr_[_pID].lrnd); temp_eth = ((plyr_[_pID].win).add((plyr_[_pID].gen))).add(plyr_[_pID].aff); plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; plyr_[_pID].win = temp_eth; } // 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(SPCdatasets.EventReturns memory _eventData_) private returns (SPCdatasets.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, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(30)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); // 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); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_p3d.sub(_p3d / 2)); admin.transfer(_com); _res = _res.add(_p3d / 2); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // 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_.P3DAmount = _p3d; _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 distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, SPCdatasets.EventReturns memory _eventData_) private returns(SPCdatasets.EventReturns) { // pay 3% out to community rewards uint256 _p3d = (_eth/100).mul(3); // distribute share to affiliate // 5%:3%:2% uint256 _aff_cent = (_eth) / 100; uint256 tempID = _affID; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered // 5% if (tempID != _pID && plyr_[tempID].name != '') { plyr_[tempID].aff = (_aff_cent.mul(5)).add(plyr_[tempID].aff); emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(5), now); } else { _p3d = _p3d.add(_aff_cent.mul(5)); } tempID = PlayerBook.getPlayerID(plyr_[tempID].addr); tempID = PlayerBook.getPlayerLAff(tempID); if (tempID != _pID && plyr_[tempID].name != '') { plyr_[tempID].aff = (_aff_cent.mul(3)).add(plyr_[tempID].aff); emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(3), now); } else { _p3d = _p3d.add(_aff_cent.mul(3)); } tempID = PlayerBook.getPlayerID(plyr_[tempID].addr); tempID = PlayerBook.getPlayerLAff(tempID); if (tempID != _pID && plyr_[tempID].name != '') { plyr_[tempID].aff = (_aff_cent.mul(2)).add(plyr_[tempID].aff); emit SPCevents.onAffiliatePayout(tempID, plyr_[tempID].addr, plyr_[tempID].name, _rID, _pID, _aff_cent.mul(2), now); } else { _p3d = _p3d.add(_aff_cent.mul(2)); } // pay out p3d _p3d = _p3d.add((_eth.mul(fees_[2].p3d)) / (100)); if (_p3d > 0) { admin.transfer(_p3d); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } /** * @dev */ function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit SPCevents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, SPCdatasets.EventReturns memory _eventData_) private returns(SPCdatasets.EventReturns) { // calculate gen share,80% uint256 _gen = (_eth.mul(fees_[2].gen)) / 100; // pot 5% uint256 _pot = (_eth.mul(5)) / 100; // 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(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, SPCdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (2 * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit SPCevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _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; //uint256 public pre_active_time = 0; uint256 public pre_active_time = 1534412700; /** * @dev return active flag 、time * @return active flag * @return active time * @return system time */ function getRunInfo() public view returns(bool, uint256, uint256) { return ( activated_, //0 pre_active_time, //1 now //2 ); } function setPreActiveTime(uint256 _pre_time) public { // only team just can activate require(msg.sender == admin, "only admin can activate"); pre_active_time = _pre_time; } function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "SuperCard already activated"); // activate the contract activated_ = true; //activated_ = false; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== function calckeys(uint256 _eth) pure public returns(uint256) { return ( (_eth).mul(100) ); } /** * @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 calceth(uint256 _keys) pure public returns(uint256) { return( (_keys)/100 ); } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library SPCdatasets { //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 P3DAmount; // amount distributed to p3d 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 uint256 gen2; // general for clear keys } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 jionflag; // player not jion round 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 uint256 attendNum; // number of players attend } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== 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); } /** * @title -Name Filter- v0.1.9 */ 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; } }
calculates how much eth would be in contract given a number of keys _keys number of keys "in contract" return eth that would exists/
function calceth(uint256 _keys) pure public returns(uint256) { return( (_keys)/100 ); }
12,253,408
pragma solidity 0.5.10; import 'ROOT/libraries/IERC1820Registry.sol'; import 'ROOT/trading/IShareToken.sol'; import 'ROOT/libraries/token/VariableSupplyToken.sol'; import 'ROOT/libraries/ITyped.sol'; import 'ROOT/libraries/Initializable.sol'; import 'ROOT/reporting/IMarket.sol'; import 'ROOT/trading/IProfitLoss.sol'; import 'ROOT/IAugur.sol'; /** * @title Share Token * @notice Storage of all data associated with orders */ contract ShareToken is ITyped, Initializable, VariableSupplyToken, IShareToken { string constant public name = "Shares"; string constant public symbol = "SHARE"; IMarket private market; uint256 private outcome; IAugur public augur; address public createOrder; address public fillOrder; address public cancelOrder; address public completeSets; address public claimTradingProceeds; IProfitLoss public profitLoss; bool private shouldUpdatePL; modifier doesNotUpdatePL() { shouldUpdatePL = false; _; shouldUpdatePL = true; } function initialize(IAugur _augur, IMarket _market, uint256 _outcome, address _erc1820RegistryAddress) external beforeInitialized { endInitialization(); market = _market; outcome = _outcome; augur = _augur; shouldUpdatePL = true; createOrder = _augur.lookup("CreateOrder"); fillOrder = _augur.lookup("FillOrder"); cancelOrder = _augur.lookup("CancelOrder"); completeSets = _augur.lookup("CompleteSets"); claimTradingProceeds = _augur.lookup("ClaimTradingProceeds"); profitLoss = IProfitLoss(_augur.lookup("ProfitLoss")); erc1820Registry = IERC1820Registry(_erc1820RegistryAddress); initialize1820InterfaceImplementations(); } function createShares(address _owner, uint256 _fxpValue) external returns(bool) { require(msg.sender == completeSets); mint(_owner, _fxpValue); return true; } function destroyShares(address _owner, uint256 _fxpValue) external returns(bool) { require(msg.sender == completeSets || msg.sender == claimTradingProceeds); burn(_owner, _fxpValue); return true; } function trustedOrderTransfer(address _source, address _destination, uint256 _attotokens) public doesNotUpdatePL returns (bool) { require(msg.sender == createOrder); return internalNoHooksTransfer(_source, _destination, _attotokens); } function trustedFillOrderTransfer(address _source, address _destination, uint256 _attotokens) public doesNotUpdatePL returns (bool) { require(msg.sender == fillOrder); // We do not call ERC777 hooks here as it would allow a malicious order creator to halt trading return internalNoHooksTransfer(_source, _destination, _attotokens); } function trustedCancelOrderTransfer(address _source, address _destination, uint256 _attotokens) public doesNotUpdatePL returns (bool) { require(msg.sender == cancelOrder); return internalNoHooksTransfer(_source, _destination, _attotokens); } function getTypeName() public view returns(bytes32) { return "ShareToken"; } /** * @return The market associated with this Share Token */ function getMarket() external view returns(IMarket) { return market; } /** * @return The outcome associated with this Share Token */ function getOutcome() external view returns(uint256) { return outcome; } function onTokenTransfer(address _from, address _to, uint256 _value) internal { if (shouldUpdatePL) { profitLoss.recordExternalTransfer(_from, _to, _value); } augur.logShareTokensTransferred(market.getUniverse(), _from, _to, _value, balances[_from], balances[_to], outcome); } function onMint(address _target, uint256 _amount) internal { augur.logShareTokensMinted(market.getUniverse(), _target, _amount, totalSupply(), balances[_target], outcome); } function onBurn(address _target, uint256 _amount) internal { augur.logShareTokensBurned(market.getUniverse(), _target, _amount, totalSupply(), balances[_target], outcome); } }
return The market associated with this Share Token/
function getMarket() external view returns(IMarket) { return market; }
5,511,641
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { WrappedConvexPosition } from "./WrappedConvexPosition.sol"; import "./libraries/Authorizable.sol"; import "./interfaces/external/IConvexBooster.sol"; import "./interfaces/external/IConvexBaseRewardPool.sol"; import "./interfaces/external/ISwapRouter.sol"; import "./interfaces/external/I3CurvePoolDepositZap.sol"; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // A little hacky, but solidity complains when trying to import different IERC20 interfaces interface IERC20Decimals { function decimals() external view returns (uint8); } /** * @title Convex Asset Proxy * @notice Proxy for depositing Curve LP shares into Convex's system, and providing a shares based abstraction of ownership * @notice Integrating with Curve is quite messy due to non-standard interfaces. Some of the logic below is specific to 3CRV-LUSD */ contract ConvexAssetProxy is WrappedConvexPosition, Authorizable { using SafeERC20 for IERC20; /************************************************ * STORAGE ***********************************************/ /// @notice whether this proxy is paused or not bool public paused; /// @notice % fee keeper collects when calling harvest(). /// Upper bound is 1000 (i.e 25 would be 2.5% of the total rewards) uint256 public keeperFee; /// @notice Contains multi-hop Uniswap V3 paths for trading CRV, CVX, & any other reward tokens /// index 0 is CRV path, index 1 is CVX path bytes[] public swapPaths; /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice 3 pool curve zap (deposit contract) I3CurvePoolDepositZap public immutable curveZap; /// @notice specific pool that the zapper will deposit into under the hood address public immutable curveMetaPool; /// @notice the pool id (in Convex's system) of the underlying token uint256 public immutable pid; /// @notice address of the convex Booster contract IConvexBooster public immutable booster; /// @notice address of the convex rewards contract IConvexBaseRewardPool public immutable rewardsContract; /// @notice Address of the deposit token 'reciepts' that are given to us /// by the booster contract when we deposit the underlying token IERC20 public immutable convexDepositToken; /// @notice Uniswap V3 router contract ISwapRouter public immutable router; /// @notice address of CRV, CVX, DAI, USDC, USDT IERC20 public constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 public constant cvx = IERC20(0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B); IERC20 public constant dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 public constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 public constant usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); /************************************************ * EVENTS, STRUCTS, MODIFIERS ***********************************************/ /// @notice emit when pause status changed event PauseStatusChanged(bool indexed pauseStatus); /// @notice emit when keeper fee changed event KeeperFeeChanged(uint256 newFee); /// @notice emit when a swap path is changed event SwapPathChanged(uint256 indexed index, bytes path); /// @notice emit on a harvest event Harvested(address harvester, uint256 underlyingHarvested); /// @notice emit on a sweep event Sweeped(address destination, address[] tokensSweeped); /// @notice struct that helps define parameters for a swap struct SwapHelper { address token; // reward token we are swapping uint256 deadline; uint256 amountOutMinimum; } /// @notice helper in constructor to avoid stack too deep /** * curveZap - address of 3pool Deposit Zap * curveMetaPool - underlying curve pool * booster address of convex booster for underlying token * rewardsContract address of convex rewards contract for underlying token * convexDepositToken address of convex deposit token reciept minted by booster * router address of Uniswap v3 router * pid pool id of the underlying token (in the context of Convex's system) * keeperFee the fee that a keeper recieves from calling harvest() */ struct constructorParams { I3CurvePoolDepositZap curveZap; address curveMetaPool; IConvexBooster booster; IConvexBaseRewardPool rewardsContract; address convexDepositToken; ISwapRouter router; uint256 pid; uint256 keeperFee; } /** * @notice Sets immutables & storage variables * @dev we use a struct to pack variables to avoid a stack too deep error * @param _constructorParams packing variables to avoid stack error - see struct natspec comments * @param _crvSwapPath swap path for CRV token * @param _cvxSwapPath swap path for CVX token * @param _token The underlying token. This token should revert in the event of a transfer failure * @param _name The name of the token (shares) created by this contract * @param _symbol The symbol of the token (shares) created by this contract * @param _governance Governance address that can perform critical functions * @param _pauser Address that can pause this contract */ constructor( constructorParams memory _constructorParams, bytes memory _crvSwapPath, bytes memory _cvxSwapPath, address _token, string memory _name, string memory _symbol, address _governance, address _pauser ) WrappedConvexPosition(_token, _name, _symbol) Authorizable() { // Authorize the pauser _authorize(_pauser); // set the owner setOwner(_governance); // Set curve zap contract curveZap = _constructorParams.curveZap; // Set the metapool curveMetaPool = _constructorParams.curveMetaPool; // Set the booster booster = _constructorParams.booster; // Set the rewards contract rewardsContract = _constructorParams.rewardsContract; // Set convexDepositToken convexDepositToken = IERC20(_constructorParams.convexDepositToken); // Set uni v3 router address router = _constructorParams.router; // Set the pool id pid = _constructorParams.pid; // set keeper fee keeperFee = _constructorParams.keeperFee; // Add the swap paths _addSwapPath(_crvSwapPath); _addSwapPath(_cvxSwapPath); // Approve the booster so it can pull tokens from this address IERC20(_token).safeApprove( address(_constructorParams.booster), type(uint256).max ); // We want our shares decimals to be the same as the convex deposit token decimals require( decimals == IERC20Decimals(_constructorParams.convexDepositToken) .decimals(), "Inconsistent decimals" ); } /// @notice Checks that the contract has not been paused modifier notPaused() { require(!paused, "Paused"); _; } /** * @notice Deposits underlying token into booster contract & auto stakes the deposit tokens received in the rewardContract * @return Tuple (the shares to mint, amount of underlying token deposited) */ function _deposit() internal override notPaused returns (uint256, uint256) { // Get the amount deposited uint256 amount = token.balanceOf(address(this)); // // See how many deposit tokens we currently have // uint256 depositTokensBefore = rewardsContract.balanceOf(address(this)); // Shares to be minted = (amount deposited * total shares) / total underlying token controlled by this contract // Note that convex deposit receipt tokens and underlying are in a 1:1 relationship // i.e for every 1 underlying we deposit we'd be credited with 1 deposit receipt token // So we can calculate the total amount deposited in underlying by querying for our balance of deposit receipt token uint256 sharesToMint; if (totalSupply != 0) { sharesToMint = (amount * totalSupply) / rewardsContract.balanceOf(address(this)); } else { // Reach this case if we have no shares sharesToMint = amount; } // Deposit underlying tokens // Last boolean indicates whether we want the Booster to auto-stake our deposit tokens in the reward contract for us booster.deposit(pid, amount, true); // Return the amount of shares the user has produced, and the amount used for it. return (sharesToMint, amount); } /** * @notice Calculates the amount of underlying token out & transfers it to _destination * @dev Shares must be burned AFTER this function is called to ensure bookkeeping is correct * @param _shares The number of wrapped position shares to withdraw * @param _destination The address to send the output funds * @return returns the amount of underlying tokens withdrawn */ function _withdraw( uint256 _shares, address _destination, uint256 ) internal override notPaused returns (uint256) { // We need to withdraw from the rewards contract & send to the destination // Boolean indicates that we don't want to collect rewards (this saves the user gas) uint256 amountUnderlyingToWithdraw = _sharesToUnderlying(_shares); rewardsContract.withdrawAndUnwrap(amountUnderlyingToWithdraw, false); // Transfer underlying LP tokens to user token.transfer(_destination, amountUnderlyingToWithdraw); // Return the amount of underlying return amountUnderlyingToWithdraw; } /** * @notice Get the underlying amount of tokens per shares given * @param _shares The amount of shares you want to know the value of * @return Value of shares in underlying token */ function _sharesToUnderlying(uint256 _shares) internal view override returns (uint256) { return (_shares * _pricePerShare()) / (10**decimals); } /** * @notice Get the amount of underlying per share in the vault * @return returns the amount of underlying tokens per share */ function _pricePerShare() internal view returns (uint256) { // Underlying per share = (1 / total Shares) * total amount of underlying controlled return ((10**decimals) * rewardsContract.balanceOf(address(this))) / totalSupply; } /** * @notice Reset approval for booster contract */ function approve() external { // We need to reset to 0 and then approve again // see https://curve.readthedocs.io/exchange-lp-tokens.html#CurveToken.approve token.approve(address(booster), 0); token.approve(address(booster), type(uint256).max); } /** * @notice Allows an authorized address or the owner to pause this contract * @param pauseStatus true for paused, false for not paused * @dev the caller must be authorized */ function pause(bool pauseStatus) external onlyAuthorized { paused = pauseStatus; emit PauseStatusChanged(pauseStatus); } /** * @notice sets a new keeper fee, only callable by owner * @param newFee the new keeper fee to set */ function setKeeperFee(uint256 newFee) external onlyOwner { keeperFee = newFee; emit KeeperFeeChanged(newFee); } /** * @notice Add a swap path * @param path new path to use for swapping */ function _addSwapPath(bytes memory path) internal { // Push dummy path to expand array, then call setPath swapPaths.push(""); _setSwapPath(swapPaths.length - 1, path); } /** * @notice Allows an authorized address to add a swap path * @param path new path to use for swapping * @dev the caller must be authorized */ function addSwapPath(bytes memory path) external onlyAuthorized { _addSwapPath(path); } /** * @notice Allows an authorized address to delete a swap path * @dev note we only allow deleting the last path to avoid a gap in our array * If a path besides the last path must be deleted, deletePath & addSwapPath will have to be called * in an appropriate order */ function deleteSwapPath() external onlyAuthorized { delete swapPaths[swapPaths.length - 1]; } /** * @notice Sets a new swap path * @param index index in swapPaths array to overwrite * @param path new path to use for swapping */ function _setSwapPath(uint256 index, bytes memory path) internal { // Multihop paths are of the form [tokenA, fee, tokenB, fee, tokenC, ... finalToken] // Let's ensure that a compromised authorized address cannot rug // by verifying that the input & output tokens are whitelisted (ie output is part of 3CRV pool - DAI, USDC, or USDT) address inputToken; address outputToken; uint256 lengthOfPath = path.length; assembly { // skip length (first 32 bytes) to load in the next 32 bytes. Now truncate to get only first 20 bytes // Address is 20 bytes, and truncates by taking the last 20 bytes of a 32 byte word. // So, we shift right by 12 bytes (96 bits) inputToken := shr(96, mload(add(path, 0x20))) // get the last 20 bytes of path // This is skip first 32 bytes, move to end of path array, then move back 20 to start of final outputToken address // Truncate to only get first 20 bytes outputToken := shr( 96, mload(sub(add(add(path, 0x20), lengthOfPath), 0x14)) ) } if (index == 0 || index == 1) { require( inputToken == address(crv) || inputToken == address(cvx), "Invalid input token" ); } require( outputToken == address(dai) || outputToken == address(usdc) || outputToken == address(usdt), "Invalid output token" ); // Set the swap path swapPaths[index] = path; emit SwapPathChanged(index, path); } /** * @notice Allows an authorized address to set the swap path for this contract * @param index index in swapPaths array to overwrite * @param path new path to use for swapping * @dev the caller must be authorized */ function setSwapPath(uint256 index, bytes memory path) public onlyAuthorized { _setSwapPath(index, path); } /** * @notice approves curve zap (deposit) contract for all 3 stable coins * @dev note that safeApprove requires us to set approval to 0 & then the desired value */ function _approveAll() internal { dai.safeApprove(address(curveZap), 0); dai.safeApprove(address(curveZap), type(uint256).max); usdc.safeApprove(address(curveZap), 0); usdc.safeApprove(address(curveZap), type(uint256).max); usdt.safeApprove(address(curveZap), 0); usdt.safeApprove(address(curveZap), type(uint256).max); } /** * @notice harvest logic to collect rewards in CRV, CVX, etc. The caller will receive a % of rewards (set by keeperFee) * @param swapHelpers a list of structs, one for each swap to be made, defining useful parameters * @dev keeper will receive all rewards in the underlying token * @dev most importantly, each SwapParams should have a reasonable amountOutMinimum to prevent egregious sandwich attacks or frontrunning * @dev we must have a swapPaths path for each reward token we wish to swap */ function harvest(SwapHelper[] memory swapHelpers) external onlyAuthorized { // Collect our rewards, will also collect extra rewards rewardsContract.getReward(); SwapHelper memory currParamHelper; ISwapRouter.ExactInputParams memory params; uint256 rewardTokenEarned; // Let's swap all the tokens we need to for (uint256 i = 0; i < swapHelpers.length; i++) { currParamHelper = swapHelpers[i]; IERC20 rewardToken = IERC20(currParamHelper.token); // Check to make sure that this isn't the underlying token or the deposit token require( address(rewardToken) != address(token) && address(rewardToken) != address(convexDepositToken), "Attempting to swap underlying or deposit token" ); rewardTokenEarned = rewardToken.balanceOf(address(this)); if (rewardTokenEarned > 0) { // Approve router to use our rewardToken rewardToken.safeApprove(address(router), rewardTokenEarned); // Create params for the swap currParamHelper = swapHelpers[i]; params = ISwapRouter.ExactInputParams({ path: swapPaths[i], recipient: address(this), deadline: currParamHelper.deadline, amountIn: rewardTokenEarned, amountOutMinimum: currParamHelper.amountOutMinimum }); router.exactInput(params); } } // First give approval to the curve zap contract to access our stable coins _approveAll(); uint256 daiBalance = dai.balanceOf(address(this)); uint256 usdcBalance = usdc.balanceOf(address(this)); uint256 usdtBalance = usdt.balanceOf(address(this)); curveZap.add_liquidity( curveMetaPool, [0, daiBalance, usdcBalance, usdtBalance], 0 ); // See how many underlying tokens we received uint256 underlyingReceived = token.balanceOf(address(this)); // Transfer keeper Fee to msg.sender // Bounty = (keeper Fee / 1000) * underlying Received uint256 bounty = (keeperFee * underlyingReceived) / 1e3; token.transfer(msg.sender, bounty); // Now stake the newly recieved underlying to the booster contract booster.deposit(pid, token.balanceOf(address(this)), true); emit Harvested(msg.sender, underlyingReceived); } /** * @notice sweeps this contract to rescue any tokens that we do not handle * Could deal with reward tokens we didn't account for, airdropped tokens, etc. * @param tokensToSweep array of token address to transfer to destination * @param destination the address to send all recovered tokens to */ function sweep(address[] memory tokensToSweep, address destination) external onlyOwner { for (uint256 i = 0; i < tokensToSweep.length; i++) { IERC20(tokensToSweep[i]).safeTransfer( destination, IERC20(tokensToSweep[i]).balanceOf(address(this)) ); } emit Sweeped(destination, tokensToSweep); } }
approves curve zap (deposit) contract for all 3 stable coins note that safeApprove requires us to set approval to 0 & then the desired value/
function _approveAll() internal { dai.safeApprove(address(curveZap), 0); dai.safeApprove(address(curveZap), type(uint256).max); usdc.safeApprove(address(curveZap), 0); usdc.safeApprove(address(curveZap), type(uint256).max); usdt.safeApprove(address(curveZap), 0); usdt.safeApprove(address(curveZap), type(uint256).max); }
1,071,978
/* ___ _ ___ _ | .\ ___ _ _ <_> ___ | __><_>._ _ ___ ._ _ ___ ___ | _// ._>| '_>| ||___|| _> | || ' |<_> || ' |/ | '/ ._> |_| \___.|_| |_| |_| |_||_|_|<___||_|_|\_|_.\___. * PeriFinance: ExternalTokenStakeManager.sol * * Latest source (may be newer): https://github.com/perifinance/peri-finance/blob/master/contracts/ExternalTokenStakeManager.sol * Docs: Will be added in the future. * https://docs.peri.finance/contracts/source/contracts/ExternalTokenStakeManager * * Contract Dependencies: * - IAddressResolver * - MixinResolver * - Owned * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 PeriFinance * * 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 */ pragma solidity 0.5.16; // https://docs.peri.finance/contracts/source/contracts/owned contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // https://docs.peri.finance/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getPynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } // https://docs.peri.finance/contracts/source/interfaces/ipynth interface IPynth { // Views function currencyKey() external view returns (bytes32); function transferablePynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to PeriFinance function burn(address account, uint amount) external; function issue(address account, uint amount) external; } // https://docs.peri.finance/contracts/source/interfaces/iissuer interface IIssuer { // Views function anyPynthOrPERIRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availablePynthCount() external view returns (uint); function availablePynths(uint index) external view returns (IPynth); function canBurnPynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function externalTokenLimit() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuablePynths(address issuer) external view returns (uint maxIssuable); function externalTokenQuota( address _account, uint _addtionalpUSD, uint _addtionalExToken, bool _isIssue ) external view returns (uint); function maxExternalTokenStakeAmount(address _account, bytes32 _currencyKey) external view returns (uint issueAmountToQuota, uint stakeAmountToQuota); function minimumStakeTime() external view returns (uint); function remainingIssuablePynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function pynths(bytes32 currencyKey) external view returns (IPynth); function getPynths(bytes32[] calldata currencyKeys) external view returns (IPynth[] memory); function pynthsByAddress(address pynthAddress) external view returns (bytes32); function totalIssuedPynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferablePeriFinanceAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to PeriFinance function issuePynths( address _issuer, bytes32 _currencyKey, uint _issueAmount ) external; function issueMaxPynths(address _issuer) external; function issuePynthsToMaxQuota(address _issuer, bytes32 _currencyKey) external; function burnPynths( address _from, bytes32 _currencyKey, uint _burnAmount ) external; function fitToClaimable(address _from) external; function exit(address _from) external; function liquidateDelinquentAccount( address account, uint pusdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getPynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.pynths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.peri.finance/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name))); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.peri.finance/contracts/source/interfaces/iflexiblestorage interface IFlexibleStorage { // Views function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint); function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory); function getIntValue(bytes32 contractName, bytes32 record) external view returns (int); function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory); function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address); function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory); function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool); function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory); function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32); function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory); // Mutative functions function deleteUIntValue(bytes32 contractName, bytes32 record) external; function deleteIntValue(bytes32 contractName, bytes32 record) external; function deleteAddressValue(bytes32 contractName, bytes32 record) external; function deleteBoolValue(bytes32 contractName, bytes32 record) external; function deleteBytes32Value(bytes32 contractName, bytes32 record) external; function setUIntValue( bytes32 contractName, bytes32 record, uint value ) external; function setUIntValues( bytes32 contractName, bytes32[] calldata records, uint[] calldata values ) external; function setIntValue( bytes32 contractName, bytes32 record, int value ) external; function setIntValues( bytes32 contractName, bytes32[] calldata records, int[] calldata values ) external; function setAddressValue( bytes32 contractName, bytes32 record, address value ) external; function setAddressValues( bytes32 contractName, bytes32[] calldata records, address[] calldata values ) external; function setBoolValue( bytes32 contractName, bytes32 record, bool value ) external; function setBoolValues( bytes32 contractName, bytes32[] calldata records, bool[] calldata values ) external; function setBytes32Value( bytes32 contractName, bytes32 record, bytes32 value ) external; function setBytes32Values( bytes32 contractName, bytes32[] calldata records, bytes32[] calldata values ) external; } // Internal references // https://docs.peri.finance/contracts/source/contracts/mixinsystemsettings contract MixinSystemSettings is MixinResolver { bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings"; bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs"; bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor"; bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio"; bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration"; bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold"; bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay"; bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio"; bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty"; bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod"; bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate"; bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime"; bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags"; bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled"; bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime"; bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit"; bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit"; bytes32 internal constant SETTING_EXTERNAL_TOKEN_QUOTA = "externalTokenQuota"; bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage"; enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal} constructor(address _resolver) internal MixinResolver(_resolver) {} function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](1); addresses[0] = CONTRACT_FLEXIBLESTORAGE; } function flexibleStorage() internal view returns (IFlexibleStorage) { return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE)); } function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) { if (gasLimitType == CrossDomainMessageGasLimits.Deposit) { return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) { return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Reward) { return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT; } else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) { return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT; } else { revert("Unknown gas limit type"); } } function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType)); } function getTradingRewardsEnabled() internal view returns (bool) { return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED); } function getWaitingPeriodSecs() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS); } function getPriceDeviationThresholdFactor() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR); } function getIssuanceRatio() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO); } function getFeePeriodDuration() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION); } function getTargetThreshold() internal view returns (uint) { // lookup on flexible storage directly for gas savings (rather than via SystemSettings) return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD); } function getLiquidationDelay() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY); } function getLiquidationRatio() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO); } function getLiquidationPenalty() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY); } function getRateStalePeriod() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD); } function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) { return flexibleStorage().getUIntValue( SETTING_CONTRACT_NAME, keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey)) ); } function getMinimumStakeTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME); } function getAggregatorWarningFlags() internal view returns (address) { return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS); } function getDebtSnapshotStaleTime() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME); } function getExternalTokenQuota() internal view returns (uint) { return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_EXTERNAL_TOKEN_QUOTA); } } // https://docs.peri.finance/contracts/source/contracts/limitedsetup contract LimitedSetup { uint public setupExpiryTime; /** * @dev LimitedSetup Constructor. * @param setupDuration The time the setup period will last for. */ constructor(uint setupDuration) internal { setupExpiryTime = now + setupDuration; } modifier onlyDuringSetup { require(now < setupExpiryTime, "Can only perform this action during setup"); _; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Libraries // https://docs.peri.finance/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @dev Round down the value with given number */ function roundDownDecimal(uint x, uint d) internal pure returns (uint) { return x.div(10**d).mul(10**d); } /** * @dev Round up the value with given number */ function roundUpDecimal(uint x, uint d) internal pure returns (uint) { uint _decimal = 10**d; if (x % _decimal > 0) { x = x.add(10**d); } return x.div(_decimal).mul(_decimal); } } // https://docs.peri.finance/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface IStakingState { // Mutative function stake( bytes32 _currencyKey, address _account, uint _amount ) external; function unstake( bytes32 _currencyKey, address _account, uint _amount ) external; function refund( bytes32 _currencyKey, address _account, uint _amount ) external returns (bool); // View function targetTokens(bytes32 _currencyKey) external view returns ( address tokenAddress, uint8 decimals, bool activated ); function stakedAmountOf(bytes32 _currencyKey, address _account) external view returns (uint); function totalStakedAmount(bytes32 _currencyKey) external view returns (uint); function totalStakerCount(bytes32 _currencyKey) external view returns (uint); function tokenList(uint _index) external view returns (bytes32); function tokenAddress(bytes32 _currencyKey) external view returns (address); function tokenDecimals(bytes32 _currencyKey) external view returns (uint8); function tokenActivated(bytes32 _currencyKey) external view returns (bool); function getTokenCurrencyKeys() external view returns (bytes32[] memory); } // https://docs.peri.finance/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } contract ExternalTokenStakeManager is Owned, MixinResolver, MixinSystemSettings, LimitedSetup(8 weeks) { using SafeMath for uint; using SafeDecimalMath for uint; IStakingState public stakingState; bytes32 internal constant pUSD = "pUSD"; bytes32 internal constant PERI = "PERI"; bytes32 internal constant USDC = "USDC"; bytes32 public constant CONTRACT_NAME = "ExternalTokenStakeManager"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_EXRATES = "ExchangeRates"; // This key order is used from unstaking multiple coins bytes32[] public currencyKeyOrder; constructor( address _owner, address _stakingState, address _resolver ) public Owned(_owner) MixinSystemSettings(_resolver) { stakingState = IStakingState(_stakingState); } function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired(); bytes32[] memory newAddresses = new bytes32[](2); newAddresses[0] = CONTRACT_ISSUER; newAddresses[1] = CONTRACT_EXRATES; return combineArrays(existingAddresses, newAddresses); } function tokenInstance(bytes32 _currencyKey) internal view tokenRegistered(_currencyKey) returns (IERC20) { return IERC20(stakingState.tokenAddress(_currencyKey)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function exchangeRates() internal view returns (IExchangeRates) { return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES)); } function getTokenList() external view returns (bytes32[] memory) { return stakingState.getTokenCurrencyKeys(); } function getTokenAddress(bytes32 _currencyKey) external view returns (address) { return stakingState.tokenAddress(_currencyKey); } function getTokenDecimals(bytes32 _currencyKey) external view returns (uint8) { return stakingState.tokenDecimals(_currencyKey); } function getTokenActivation(bytes32 _currencyKey) external view returns (bool) { return stakingState.tokenActivated(_currencyKey); } function getCurrencyKeyOrder() external view returns (bytes32[] memory) { return currencyKeyOrder; } function combinedStakedAmountOf(address _user, bytes32 _unitCurrency) external view returns (uint) { return _combinedStakedAmountOf(_user, _unitCurrency); } function stakedAmountOf( address _user, bytes32 _currencyKey, bytes32 _unitCurrency ) external view returns (uint) { if (_currencyKey == _unitCurrency) { return stakingState.stakedAmountOf(_currencyKey, _user); } else { return _toCurrency(_currencyKey, _unitCurrency, stakingState.stakedAmountOf(_currencyKey, _user)); } } function _combinedStakedAmountOf(address _user, bytes32 _unitCurrency) internal view returns (uint combinedStakedAmount) { bytes32[] memory tokenList = stakingState.getTokenCurrencyKeys(); for (uint i = 0; i < tokenList.length; i++) { uint _stakedAmount = stakingState.stakedAmountOf(tokenList[i], _user); if (_stakedAmount == 0) { continue; } uint stakedAmount = _toCurrency(tokenList[i], _unitCurrency, _stakedAmount); combinedStakedAmount = combinedStakedAmount.add(stakedAmount); } } function _toCurrency( bytes32 _fromCurrencyKey, bytes32 _toCurrencyKey, uint _amount ) internal view returns (uint) { if (_fromCurrencyKey == _toCurrencyKey) { return _amount; } uint amountToUSD; if (_fromCurrencyKey == pUSD) { amountToUSD = _amount; } else { (uint toUSDRate, bool fromCurrencyRateIsInvalid) = exchangeRates().rateAndInvalid(_fromCurrencyKey); _requireRatesNotInvalid(fromCurrencyRateIsInvalid); amountToUSD = _amount.multiplyDecimalRound(toUSDRate); } if (_toCurrencyKey == pUSD) { return amountToUSD; } else { (uint toCurrencyRate, bool toCurrencyRateIsInvalid) = exchangeRates().rateAndInvalid(_toCurrencyKey); _requireRatesNotInvalid(toCurrencyRateIsInvalid); return amountToUSD.divideDecimalRound(toCurrencyRate); } } /** * @notice Utils checking given two key arrays' value are matching each other(its order will not be considered). */ function _keyChecker(bytes32[] memory _keysA, bytes32[] memory _keysB) internal pure returns (bool) { if (_keysA.length != _keysB.length) { return false; } for (uint i = 0; i < _keysA.length; i++) { bool exist; for (uint j = 0; j < _keysA.length; j++) { if (_keysA[i] == _keysB[j]) { exist = true; break; } } // given currency key is not matched if (!exist) { return false; } } return true; } function stake( address _staker, uint _amount, bytes32 _targetCurrency, bytes32 _inputCurrency ) external onlyIssuer { uint stakingAmountConverted = _toCurrency(_inputCurrency, _targetCurrency, _amount); uint targetDecimals = stakingState.tokenDecimals(_targetCurrency); require(targetDecimals <= 18, "Invalid decimal number"); uint stakingAmountConvertedRoundedUp = stakingAmountConverted.roundUpDecimal(uint(18).sub(targetDecimals)); require( tokenInstance(_targetCurrency).transferFrom( _staker, address(stakingState), stakingAmountConvertedRoundedUp.div(10**(uint(18).sub(targetDecimals))) ), "Transferring staking token has been failed" ); stakingState.stake(_targetCurrency, _staker, stakingAmountConvertedRoundedUp); } function unstake( address _unstaker, uint _amount, bytes32 _targetCurrency, bytes32 _inputCurrency ) external onlyIssuer { uint unstakingAmountConverted = _toCurrency(_inputCurrency, _targetCurrency, _amount); _unstakeAndRefund(_unstaker, unstakingAmountConverted, _targetCurrency); } /** * @notice It unstakes multiple tokens by pre-defined order. * * @param _unstaker unstaker address * @param _amount amount to unstake * @param _inputCurrency the currency unit of _amount * * @dev bytes32 variable "order" is only able to be assigned by setUnstakingOrder(), * and it checks its conditions there, here won't check its validation. */ function unstakeMultipleTokens( address _unstaker, uint _amount, bytes32 _inputCurrency ) external onlyIssuer { bytes32[] memory currencyKeys = stakingState.getTokenCurrencyKeys(); bytes32[] memory order; if (!_keyChecker(currencyKeys, currencyKeyOrder)) { order = currencyKeys; } else { order = currencyKeyOrder; } uint combinedStakedAmount = _combinedStakedAmountOf(_unstaker, _inputCurrency); require(combinedStakedAmount >= _amount, "Combined staked amount is not enough"); uint[] memory unstakeAmountByCurrency = new uint[](order.length); for (uint i = 0; i < order.length; i++) { uint stakedAmountByCurrency = stakingState.stakedAmountOf(order[i], _unstaker); // Becacuse of exchange rate calculation error, // input amount is converted into each currency key rather than converting staked amount. uint amountConverted = _toCurrency(_inputCurrency, order[i], _amount); if (stakedAmountByCurrency < amountConverted) { // If staked amount is lower than amount to unstake, all staked amount will be unstaked. unstakeAmountByCurrency[i] = stakedAmountByCurrency; amountConverted = amountConverted.sub(stakedAmountByCurrency); _amount = _toCurrency(order[i], _inputCurrency, amountConverted); } else { unstakeAmountByCurrency[i] = amountConverted; _amount = 0; } if (_amount == 0) { break; } } for (uint i = 0; i < order.length; i++) { if (unstakeAmountByCurrency[i] == 0) { continue; } _unstakeAndRefund(_unstaker, unstakeAmountByCurrency[i], order[i]); } } function _unstakeAndRefund( address _unstaker, uint _amount, bytes32 _targetCurrency ) internal tokenRegistered(_targetCurrency) { uint targetDecimals = stakingState.tokenDecimals(_targetCurrency); require(targetDecimals <= 18, "Invalid decimal number"); uint unstakingAmountConvertedRoundedUp = _amount.roundUpDecimal(uint(18).sub(targetDecimals)); stakingState.unstake(_targetCurrency, _unstaker, unstakingAmountConvertedRoundedUp); require( stakingState.refund(_targetCurrency, _unstaker, unstakingAmountConvertedRoundedUp), "Refund has been failed" ); } function setUnstakingOrder(bytes32[] calldata _order) external onlyOwner { bytes32[] memory currencyKeys = stakingState.getTokenCurrencyKeys(); require(_keyChecker(currencyKeys, _order), "Given currency keys are not available"); currencyKeyOrder = _order; } function setStakingState(address _stakingState) external onlyOwner { stakingState = IStakingState(_stakingState); } function _requireRatesNotInvalid(bool anyRateIsInvalid) internal pure { require(!anyRateIsInvalid, "A pynth or PERI rate is invalid"); } function _onlyIssuer() internal view { require(msg.sender == address(issuer()), "Sender is not Issuer"); } function _tokenRegistered(bytes32 _currencyKey) internal view { require(stakingState.tokenAddress(_currencyKey) != address(0), "Target token is not registered"); } modifier onlyIssuer() { _onlyIssuer(); _; } modifier tokenRegistered(bytes32 _currencyKey) { _tokenRegistered(_currencyKey); _; } }
It unstakes multiple tokens by pre-defined order. _unstaker unstaker address _amount amount to unstake _inputCurrency the currency unit of _amount bytes32 variable "order" is only able to be assigned by setUnstakingOrder(), and it checks its conditions there, here won't check its validation./ Becacuse of exchange rate calculation error, input amount is converted into each currency key rather than converting staked amount. If staked amount is lower than amount to unstake, all staked amount will be unstaked.
function unstakeMultipleTokens( address _unstaker, uint _amount, bytes32 _inputCurrency ) external onlyIssuer { bytes32[] memory currencyKeys = stakingState.getTokenCurrencyKeys(); bytes32[] memory order; if (!_keyChecker(currencyKeys, currencyKeyOrder)) { order = currencyKeys; order = currencyKeyOrder; } uint combinedStakedAmount = _combinedStakedAmountOf(_unstaker, _inputCurrency); require(combinedStakedAmount >= _amount, "Combined staked amount is not enough"); uint[] memory unstakeAmountByCurrency = new uint[](order.length); for (uint i = 0; i < order.length; i++) { uint stakedAmountByCurrency = stakingState.stakedAmountOf(order[i], _unstaker); uint amountConverted = _toCurrency(_inputCurrency, order[i], _amount); if (stakedAmountByCurrency < amountConverted) { unstakeAmountByCurrency[i] = stakedAmountByCurrency; amountConverted = amountConverted.sub(stakedAmountByCurrency); _amount = _toCurrency(order[i], _inputCurrency, amountConverted); unstakeAmountByCurrency[i] = amountConverted; _amount = 0; } if (_amount == 0) { break; } } for (uint i = 0; i < order.length; i++) { if (unstakeAmountByCurrency[i] == 0) { continue; } _unstakeAndRefund(_unstaker, unstakeAmountByCurrency[i], order[i]); } }
6,880,339
./full_match/1/0x5aE6b7CD9fA90808bcB6004652C64B95515Dd5D0/sources/contracts/GsERC1155.sol
Updates the URI of a given token, can be called at any time (for simple reveals) _token_id The id of the token to update _tokenURI The new URI to use for the token metadata (returned as is)
function setURI(uint256 _token_id, string memory _tokenURI) external editors tokenExist(_token_id) { token_datas[_token_id].uri = _tokenURI; }
3,130,877
./full_match/1/0xe1272adbf95FA29ab6aC9Cd8bF2D5462BCD766B3/sources/contracts/cash/CashManager.sol
Override admin function for changing the representation of the amount of CASH a user has burned to kick off redemption process user The user whose balance is being set epoch The epoch in which to set user balance for oldBalance The user's old redemption balance balance The user's new balance The total burned amount for the epoch must be set appropriately in order to correctly calculate redemptions./ Increment or decrement total burned for the epoch based on whether we are increasing or decreasing the balance.
function setPendingRedemptionBalance( address user, uint256 epoch, uint256 oldBalance, uint256 balance ) external updateEpoch onlyRole(MANAGER_ADMIN) { if (epoch > currentEpoch) { revert CannotServiceFutureEpoch(); } uint256 previousBalance = redemptionInfoPerEpoch[epoch].addressToBurnAmt[ user ]; if (oldBalance != previousBalance) { revert RedemptionBalanceMismatch(); } if (balance < previousBalance) { redemptionInfoPerEpoch[epoch].totalBurned -= previousBalance - balance; redemptionInfoPerEpoch[epoch].totalBurned += balance - previousBalance; } redemptionInfoPerEpoch[epoch].addressToBurnAmt[user] = balance; emit PendingRedemptionBalanceSet( user, epoch, balance, redemptionInfoPerEpoch[epoch].totalBurned ); } KYC FUNCTIONS
17,003,378
/* solhint-disable avoid-low-level-calls */ /* solhint-disable no-inline-assembly */ /* solhint-disable not-rely-on-time */ /* solhint-disable avoid-tx-origin */ /* solhint-disable bracket-align */ // SPDX-License-Identifier:MIT pragma solidity ^0.6.2; pragma experimental ABIEncoderV2; import "./0x/LibBytesV06.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./utils/GsnUtils.sol"; import "./interfaces/ISignatureVerifier.sol"; import "./interfaces/IRelayHub.sol"; import "./interfaces/IPaymaster.sol"; import "./interfaces/IForwarder.sol"; import "./BaseRelayRecipient.sol"; import "./StakeManager.sol"; import "./Penalizer.sol"; contract RelayHub is IRelayHub { string public override versionHub = "2.0.0-alpha.1+opengsn.hub.irelayhub"; // Minimum stake a relay can have. An attack to the network will never cost less than half this value. uint256 constant private MINIMUM_STAKE = 1 ether; // Minimum unstake delay blocks of a relay manager's stake on the StakeManager uint256 constant private MINIMUM_UNSTAKE_DELAY = 1000; // Minimum balance required for a relay to register or re-register. Prevents user error in registering a relay that // will not be able to immediately start serving requests. uint256 constant private MINIMUM_RELAY_BALANCE = 0.1 ether; // Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits. uint256 constant private MAXIMUM_RECIPIENT_DEPOSIT = 2 ether; /** * the total gas overhead of relayCall(), before the first gasleft() and after the last gasleft(). * Assume that relay has non-zero balance (costs 15'000 more otherwise). */ // Gas cost of all relayCall() instructions after actual 'calculateCharge()' uint256 constant private GAS_OVERHEAD = 34876; //gas overhead to calculate gasUseWithoutPost uint256 constant private POST_OVERHEAD = 8688; function getHubOverhead() external override view returns (uint256) { return GAS_OVERHEAD; } // Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions uint256 constant private GAS_RESERVE = 100000; // maps relay worker's address to its manager's address mapping(address => address) private workerToManager; // maps relay managers to the number of their workers mapping(address => uint256) private workerCount; uint256 constant public MAX_WORKER_COUNT = 10; mapping(address => uint256) private balances; StakeManager public stakeManager; Penalizer public penalizer; constructor (StakeManager _stakeManager, Penalizer _penalizer) public { stakeManager = _stakeManager; penalizer = _penalizer; } function getStakeManager() external override view returns(address) { return address(stakeManager); } function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external override { address relayManager = msg.sender; require( stakeManager.isRelayManagerStaked(relayManager, MINIMUM_STAKE, MINIMUM_UNSTAKE_DELAY), "relay manager not staked" ); require(workerCount[relayManager] > 0, "no relay workers"); emit RelayServerRegistered(relayManager, baseRelayFee, pctRelayFee, url); } function addRelayWorkers(address[] calldata newRelayWorkers) external override { address relayManager = msg.sender; workerCount[relayManager] = workerCount[relayManager] + newRelayWorkers.length; require(workerCount[relayManager] <= MAX_WORKER_COUNT, "too many workers"); require( stakeManager.isRelayManagerStaked(relayManager, MINIMUM_STAKE, MINIMUM_UNSTAKE_DELAY), "relay manager not staked" ); for (uint256 i = 0; i < newRelayWorkers.length; i++) { require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager"); workerToManager[newRelayWorkers[i]] = relayManager; } emit RelayWorkersAdded(relayManager, newRelayWorkers, workerCount[relayManager]); } function depositFor(address target) public override payable { uint256 amount = msg.value; require(amount <= MAXIMUM_RECIPIENT_DEPOSIT, "deposit too big"); balances[target] = SafeMath.add(balances[target], amount); emit Deposited(target, msg.sender, amount); } function balanceOf(address target) external override view returns (uint256) { return balances[target]; } function withdraw(uint256 amount, address payable dest) public override { address payable account = msg.sender; require(balances[account] >= amount, "insufficient funds"); balances[account] -= amount; dest.transfer(amount); emit Withdrawn(account, dest, amount); } function canRelay( ISignatureVerifier.RelayRequest memory relayRequest, uint256 initialGas, bytes memory signature, bytes memory approvalData ) private view returns (bool success, bytes memory returnValue, IPaymaster.GasLimits memory gasLimits) { gasLimits = IPaymaster(relayRequest.relayData.paymaster).getGasLimits(); uint256 maxPossibleGas = GAS_OVERHEAD + gasLimits.acceptRelayedCallGasLimit + gasLimits.preRelayedCallGasLimit + gasLimits.postRelayedCallGasLimit + relayRequest.gasData.gasLimit; // This transaction must have enough gas to forward the call to the recipient with the requested amount, and not // run out of gas later in this function. require( initialGas >= maxPossibleGas, "Not enough gas left for innerRelayCall to complete"); uint256 maxPossibleCharge = calculateCharge( maxPossibleGas, relayRequest.gasData ); // We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay // for the maximum possible charge. require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster], "Paymaster balance too low"); bytes memory encodedTx = abi.encodeWithSelector(IPaymaster.acceptRelayedCall.selector, relayRequest, signature, approvalData, maxPossibleGas ); (success, returnValue) = relayRequest.relayData.paymaster.staticcall{gas:gasLimits.acceptRelayedCallGasLimit}(encodedTx); } struct RelayCallData { bool success; bytes4 functionSelector; bytes recipientContext; IPaymaster.GasLimits gasLimits; RelayCallStatus status; } function relayCall( // TODO: msg.sender used to be treated as 'relay' (now passed in a struct), // make sure this does not have security impl ISignatureVerifier.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external override returns (bool paymasterAccepted, string memory revertReason) { RelayCallData memory vars; vars.functionSelector = LibBytesV06.readBytes4(relayRequest.encodedFunction, 0); require(msg.sender == tx.origin, "relay worker cannot be a smart contract"); require(workerToManager[msg.sender] != address(0), "Unknown relay worker"); require( stakeManager.isRelayManagerStaked(workerToManager[msg.sender], MINIMUM_STAKE, MINIMUM_UNSTAKE_DELAY), "relay manager not staked" ); require(relayRequest.gasData.gasPrice <= tx.gasprice, "Invalid gas price"); require(externalGasLimit <= block.gaslimit, "Impossible gas limit"); // We now verify that the paymaster will agree to be charged for the transaction. (vars.success, vars.recipientContext, vars.gasLimits) = canRelay( ISignatureVerifier.RelayRequest( relayRequest.target, relayRequest.encodedFunction, relayRequest.gasData, relayRequest.relayData), externalGasLimit, signature, approvalData); if (!vars.success) { revertReason = GsnUtils.getError(vars.recipientContext); emit TransactionRejectedByPaymaster( workerToManager[msg.sender], relayRequest.relayData.paymaster, relayRequest.relayData.senderAddress, relayRequest.target, msg.sender, vars.functionSelector, revertReason); return (vars.success, revertReason); } // From this point on, this transaction will not revert nor run out of gas, and the paymaster will be charged // for the gas spent. { //How much gas to pass down to innerRelayCall. must be lower than the default 63/64 // actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough. uint innerGasLimit = gasleft()*63/64-GAS_RESERVE; // Calls to the recipient are performed atomically inside an inner transaction which may revert in case of // errors in the recipient. In either case (revert or regular execution) the return data encodes the // RelayCallStatus value. (, bytes memory relayCallStatus) = address(this).call{gas:innerGasLimit}( abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, vars.gasLimits, innerGasLimit + externalGasLimit-gasleft() + GAS_OVERHEAD + POST_OVERHEAD, /*totalInitialGas*/ abi.decode(vars.recipientContext, (bytes))) ); vars.status = abi.decode(relayCallStatus, (RelayCallStatus)); } { // We now perform the actual charge calculation, based on the measured gas used uint256 gasUsed = (externalGasLimit - gasleft()) + GAS_OVERHEAD; uint256 charge = calculateCharge(gasUsed, relayRequest.gasData); // We've already checked that the paymaster has enough balance to pay for the relayed transaction, this is only // a sanity check to prevent overflows in case of bugs. require(balances[relayRequest.relayData.paymaster] >= charge, "Should not get here"); balances[relayRequest.relayData.paymaster] -= charge; balances[workerToManager[msg.sender]] += charge; emit TransactionRelayed( workerToManager[msg.sender], msg.sender, relayRequest.relayData.senderAddress, relayRequest.target, relayRequest.relayData.paymaster, vars.functionSelector, vars.status, charge); return (true, ""); } } struct AtomicData { uint256 balanceBefore; bytes32 preReturnValue; bool relayedCallSuccess; bytes data; } function innerRelayCall( ISignatureVerifier.RelayRequest calldata relayRequest, bytes calldata signature, IPaymaster.GasLimits calldata gasLimits, uint256 totalInitialGas, bytes calldata recipientContext ) external returns (RelayCallStatus) { AtomicData memory atomicData; // A new gas measurement is performed inside innerRelayCall, since // due to EIP150 available gas amounts cannot be directly compared across external calls // This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the // recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. require(msg.sender == address(this), "Only RelayHub should call this function"); // If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on // the recipient. The recipient will still be charged for the used gas by the relay. // The recipient is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and // post state to ensure this doesn't happen. atomicData.balanceBefore = balances[relayRequest.relayData.paymaster]; // First preRelayedCall is executed. // Note: we open a new block to avoid growing the stack too much. atomicData.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, recipientContext ); { bool success; bytes memory retData; // preRelayedCall may revert, but the recipient will still be charged: it should ensure in // acceptRelayedCall that this will not happen. (success, retData) = relayRequest.relayData.paymaster.call{gas:gasLimits.preRelayedCallGasLimit}(atomicData.data); if (!success) { revertWithStatus(RelayCallStatus.PreRelayedFailed); } atomicData.preReturnValue = abi.decode(retData, (bytes32)); } // The actual relayed call is now executed. The sender's address is appended at the end of the transaction data (atomicData.relayedCallSuccess,) = relayRequest.relayData.forwarder.call( abi.encodeWithSelector(IForwarder.verifyAndCall.selector, relayRequest, signature) ); // Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate // We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate // accounting. atomicData.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, recipientContext, atomicData.relayedCallSuccess, atomicData.preReturnValue, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.gasData ); (bool successPost,) = relayRequest.relayData.paymaster.call{gas:gasLimits.postRelayedCallGasLimit}(atomicData.data); if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed); } if (balances[relayRequest.relayData.paymaster] < atomicData.balanceBefore) { revertWithStatus(RelayCallStatus.RecipientBalanceChanged); } return atomicData.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed; } /** * @dev Reverts the transaction with return data set to the ABI encoding of the status argument. */ function revertWithStatus(RelayCallStatus status) private pure { bytes memory data = abi.encode(status); assembly { let dataSize := mload(data) let dataPtr := add(data, 32) revert(dataPtr, dataSize) } } function calculateCharge(uint256 gasUsed, ISignatureVerifier.GasData memory gasData) public override virtual view returns (uint256) { return gasData.baseRelayFee + (gasUsed * gasData.gasPrice * (100 + gasData.pctRelayFee)) / 100; } modifier penalizerOnly () { require(msg.sender == address(penalizer), "Not penalizer"); _; } function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly { address relayManager = workerToManager[relayWorker]; // The worker must be controlled by a manager with a locked stake require(relayManager != address(0), "Unknown relay worker"); require( stakeManager.isRelayManagerStaked(relayManager, MINIMUM_STAKE, MINIMUM_UNSTAKE_DELAY), "relay manager not staked" ); (uint256 totalStake, , , ) = stakeManager.stakes(relayManager); stakeManager.penalizeRelayManager(relayManager, beneficiary, totalStake); } }
A new gas measurement is performed inside innerRelayCall, since due to EIP150 available gas amounts cannot be directly compared across external calls This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on the recipient. The recipient will still be charged for the used gas by the relay. The recipient is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and post state to ensure this doesn't happen. First preRelayedCall is executed. Note: we open a new block to avoid growing the stack too much. preRelayedCall may revert, but the recipient will still be charged: it should ensure in acceptRelayedCall that this will not happen.
function innerRelayCall( ISignatureVerifier.RelayRequest calldata relayRequest, bytes calldata signature, IPaymaster.GasLimits calldata gasLimits, uint256 totalInitialGas, bytes calldata recipientContext ) external returns (RelayCallStatus) { AtomicData memory atomicData; require(msg.sender == address(this), "Only RelayHub should call this function"); atomicData.balanceBefore = balances[relayRequest.relayData.paymaster]; atomicData.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, recipientContext ); { bool success; bytes memory retData; if (!success) { revertWithStatus(RelayCallStatus.PreRelayedFailed); } atomicData.preReturnValue = abi.decode(retData, (bytes32)); } relayRequest.relayData.forwarder.call( abi.encodeWithSelector(IForwarder.verifyAndCall.selector, relayRequest, signature) ); IPaymaster.postRelayedCall.selector, recipientContext, atomicData.relayedCallSuccess, atomicData.preReturnValue, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.gasData ); if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed); } if (balances[relayRequest.relayData.paymaster] < atomicData.balanceBefore) { revertWithStatus(RelayCallStatus.RecipientBalanceChanged); } return atomicData.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed; }
2,521,620
// Sources flattened with hardhat v2.6.2 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), 'Ownable: new owner is the zero address' ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, 'Address: insufficient balance' ); (bool success, ) = recipient.call{value: amount}(''); require( success, 'Address: unable to send value, recipient may have reverted' ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'Address: low-level call with value failed' ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, 'Address: insufficient balance for call' ); require(isContract(target), 'Address: call to non-contract'); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, 'Address: low-level static call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), 'Address: static call to non-contract'); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, 'Address: low-level delegate call failed' ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), 'Address: delegate call to non-contract'); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), 'ERC721: balance query for the zero address' ); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), 'ERC721: owner query for nonexistent token' ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token' ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, 'ERC721: approval to current owner'); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), 'ERC721: approve caller is not owner nor approved for all' ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), 'ERC721: approved query for nonexistent token' ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), 'ERC721: approve to caller'); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved' ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), 'ERC721: transfer caller is not owner nor approved' ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'ERC721: transfer to non ERC721Receiver implementer' ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), 'ERC721: operator query for nonexistent token' ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ''); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), 'ERC721: transfer to non ERC721Receiver implementer' ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), 'ERC721: mint to the zero address'); require(!_exists(tokenId), 'ERC721: token already minted'); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, 'ERC721: transfer of token that is not own' ); require(to != address(0), 'ERC721: transfer to the zero address'); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( 'ERC721: transfer to non ERC721Receiver implementer' ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/[email protected] 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/token/ERC721/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require( index < ERC721.balanceOf(owner), 'ERC721Enumerable: owner index out of bounds' ); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require( index < ERC721Enumerable.totalSupply(), 'ERC721Enumerable: global index out of bounds' ); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File contracts/OpenSeaTradableNFT.sol pragma solidity ^0.8.0; contract OpenSeaOwnableDelegateProxy {} contract OpenSeaProxyRegistry { mapping(address => OpenSeaOwnableDelegateProxy) public proxies; } contract OpenSeaTradableNFT { address openSeaProxyRegistryAddress; function _setProxyRegistryAddress(address _openSeaProxyRegistryAddress) internal { openSeaProxyRegistryAddress = _openSeaProxyRegistryAddress; } function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { // Whitelist OpenSea proxy contract for easy trading. OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return false; } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/DangerNoodleNFT.sol pragma solidity ^0.8.0; contract DangerNoodleNFT is Ownable, ERC721Enumerable, OpenSeaTradableNFT { using SafeMath for uint256; string public baseURI = ''; uint256 public price = 0.04 ether; uint256 public preSaleBuyInPrice = 0.04 ether; uint256 public MAX_NOODLES = 10000; uint256 public MAX_NOODLE_PURCHASE = 10; uint256 public MAX_PRESALE_NOODLE_PURCHASE = 3; uint256 public PURCHASEABLE_PRESALES = 500; uint256 public NOODLE_RESERVE = 300; bool public preSaleIsActive = false; bool public saleIsActive = false; mapping(address => bool) public whitelist; mapping(address => uint256) public presalePurchases; address public constant devAddress = 0x6AB6B9C8ed19A464722198E8f4ef113E10c298B8; constructor( string memory _initialBaseURI, address _openSeaProxyRegistryAddress ) ERC721('Danger Noodles', 'NOODLE') { baseURI = _initialBaseURI; OpenSeaTradableNFT._setProxyRegistryAddress( _openSeaProxyRegistryAddress ); } function isApprovedForAll(address owner, address operator) public view override(ERC721, OpenSeaTradableNFT) returns (bool) { if (OpenSeaTradableNFT.isApprovedForAll(owner, operator)) { return true; } return ERC721.isApprovedForAll(owner, operator); } function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function maxAvailableForSell() public view returns (uint256) { return MAX_NOODLES.sub(NOODLE_RESERVE).sub(totalSupply()); } function mintPreSaleNoodles(uint256 numberOfTokens) external payable { require(whitelist[msg.sender], 'Whitelist required for pre sale'); require(preSaleIsActive, 'Pre sale must be active to mint Noodles'); require( presalePurchases[msg.sender].add(numberOfTokens) <= MAX_PRESALE_NOODLE_PURCHASE, 'Can only mint MAX_PRESALE_NOODLE_PURCHASE tokens during the presale' ); require( msg.value >= price.mul(numberOfTokens), 'Ether value sent is not correct' ); presalePurchases[msg.sender] = presalePurchases[msg.sender].add( numberOfTokens ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (maxAvailableForSell() > 0) { _safeMint(msg.sender, mintIndex); } } } function mintNoodles(uint256 numberOfTokens) external payable { require(saleIsActive, 'Sale must be active to mint Noodles'); require( numberOfTokens <= MAX_NOODLE_PURCHASE, 'Can only mint MAX_NOODLE_PURCHASE tokens at a time' ); require( numberOfTokens <= maxAvailableForSell(), 'Purchase would exceed max supply of Noodles' ); require( msg.value >= price.mul(numberOfTokens), 'Ether value sent is not correct' ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); if (maxAvailableForSell() > 0) { _safeMint(msg.sender, mintIndex); } } } function buyIntoPreSale() external payable { require(!whitelist[msg.sender], 'Already in whitelist'); require(!saleIsActive, 'Regular sale is already active'); require(PURCHASEABLE_PRESALES > 0, 'Pre sale sold out'); require( msg.value >= preSaleBuyInPrice, 'Ether value sent is not correct' ); PURCHASEABLE_PRESALES = PURCHASEABLE_PRESALES - 1; whitelist[msg.sender] = true; } function whitelistAddresses(address[] memory addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = true; } } function removeWhitelistAddresses(address[] memory addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { whitelist[addresses[i]] = false; } } function withdraw() external onlyOwner { uint256 balance = address(this).balance; uint256 devShare = balance.mul(30).div(100); uint256 ownerShare = balance - devShare; payable(devAddress).transfer(devShare); payable(msg.sender).transfer(ownerShare); } function flipPreSaleState() external onlyOwner { preSaleIsActive = !preSaleIsActive; } function flipSaleState() external onlyOwner { saleIsActive = !saleIsActive; } function setPrice(uint256 _price) external onlyOwner { price = _price; } function setPreSaleBuyInPrice(uint256 _price) external onlyOwner { preSaleBuyInPrice = _price; } function setBaseURI(string memory _newBaseURI) external onlyOwner { baseURI = _newBaseURI; } function reserveNoodles(uint256 numberOfTokens) external onlyOwner { require( numberOfTokens > 0 && numberOfTokens <= NOODLE_RESERVE, 'Not enough reserve left for team' ); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } NOODLE_RESERVE = NOODLE_RESERVE.sub(numberOfTokens); } }
Whitelist OpenSea proxy contract for easy trading.
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) { OpenSeaProxyRegistry openSeaProxyRegistry = OpenSeaProxyRegistry( openSeaProxyRegistryAddress ); if (address(openSeaProxyRegistry.proxies(owner)) == operator) { return true; } return false; }
1,393,914
./full_match/5/0xF129B17B76621A52e63F5f5B4D1cFED31FdfF89D/sources/lib/solady/src/utils/LibBitmap.sol
Returns number of set bits within a range by scanning `amount` of bits starting from the bit at `start`.
{ function popCount(Bitmap storage bitmap, uint256 start, uint256 amount) internal view returns (uint256 count) unchecked { uint256 bucket = start >> 8; uint256 shift = start & 0xff; if (!(amount + shift < 257)) { count = LibBit.popCount(bitmap.map[bucket] >> shift); uint256 bucketEnd = bucket + ((amount + shift) >> 8); amount = (amount + shift) & 0xff; shift = 0; for (++bucket; bucket != bucketEnd; ++bucket) { count += LibBit.popCount(bitmap.map[bucket]); } } count += LibBit.popCount((bitmap.map[bucket] >> shift) << (256 - amount)); } function popCount(Bitmap storage bitmap, uint256 start, uint256 amount) internal view returns (uint256 count) unchecked { uint256 bucket = start >> 8; uint256 shift = start & 0xff; if (!(amount + shift < 257)) { count = LibBit.popCount(bitmap.map[bucket] >> shift); uint256 bucketEnd = bucket + ((amount + shift) >> 8); amount = (amount + shift) & 0xff; shift = 0; for (++bucket; bucket != bucketEnd; ++bucket) { count += LibBit.popCount(bitmap.map[bucket]); } } count += LibBit.popCount((bitmap.map[bucket] >> shift) << (256 - amount)); } function popCount(Bitmap storage bitmap, uint256 start, uint256 amount) internal view returns (uint256 count) unchecked { uint256 bucket = start >> 8; uint256 shift = start & 0xff; if (!(amount + shift < 257)) { count = LibBit.popCount(bitmap.map[bucket] >> shift); uint256 bucketEnd = bucket + ((amount + shift) >> 8); amount = (amount + shift) & 0xff; shift = 0; for (++bucket; bucket != bucketEnd; ++bucket) { count += LibBit.popCount(bitmap.map[bucket]); } } count += LibBit.popCount((bitmap.map[bucket] >> shift) << (256 - amount)); } }
1,889,728
// 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/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for 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: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/SashimiPlates/interfaces/IUniStakingRewards.sol pragma solidity 0.6.12; interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } // File: contracts/SashimiPlates/interfaces/ISashimiPlateController.sol pragma solidity 0.6.12; interface ISashimiPlateController { function plates(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } // File: contracts/SashimiPlates/strategies/StrategyUniStakingReward.sol pragma solidity 0.6.12; contract StrategyUniStakingReward { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Staking rewards address for LP providers address public immutable rewards; // want lp tokens address public immutable want; // tokens we're farming address public immutable uni; // stablecoins address public immutable token; // weth address public immutable weth; // dex address public immutable univ2Router2; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; // UNI swap threshold uint256 public uniThreshold = 0; // Perfomance fee 4.5% uint256 public performanceFee = 450; uint256 public constant performanceMax = 10000; // Withdrawal fee 0.5% // - 0.375% to treasury // - 0.125% to dev fund uint256 public treasuryFee = 375; uint256 public constant treasuryMax = 100000; uint256 public devFundFee = 125; uint256 public constant devFundMax = 100000; address public governance; address public controller; address public strategist; address public timelock; constructor( address _governance, address _strategist, address _controller, address _timelock, address _rewards, address _token, address _weth, address _uni, address _want, address _univ2Router2 ) public { governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; rewards = _rewards; token = _token; weth = _weth; uni = _uni; want = _want; univ2Router2 = _univ2Router2; } // **** Views **** function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external pure returns (string memory) { return "StrategyUniStakingReward"; } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == governance, "!governance"); keepUNI = _keepUNI; } function setUniThreshold(uint256 _uniThreshold) external { require(msg.sender == governance, "!governance"); uniThreshold = _uniThreshold; } function setDevFundFee(uint256 _devFundFee) external { require(msg.sender == governance, "!governance"); devFundFee = _devFundFee; } function setTreasuryFee(uint256 _treasuryFee) external { require(msg.sender == governance, "!governance"); treasuryFee = _treasuryFee; } function setPerformanceFee(uint256 _performanceFee) external { require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State Mutations **** function deposit() public { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).approve(rewards, _want); IStakingRewards(rewards).stake(_want); } } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a plate withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax); IERC20(want).safeTransfer(ISashimiPlateController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax); IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _feeTreasury ); address _plate = ISashimiPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _plate = ISashimiPlateController(controller).plates(address(want)); require(_plate != address(0), "!plate"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_plate, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } function brine() public { harvest(); } function harvest() public { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if(_uni <= uniThreshold) return; if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( ISashimiPlateController(controller).treasury(), _keepUNI ); _swap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for token uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swap(weth, token, _weth.div(2)); } // Adds in liquidity for ETH/token _weth = IERC20(weth).balanceOf(address(this)); uint256 _token = IERC20(token).balanceOf(address(this)); if (_weth > 0 && _token > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token).safeApprove(univ2Router2, 0); IERC20(token).safeApprove(univ2Router2, _token); IUniswapV2Router02(univ2Router2).addLiquidity( weth, token, _weth, _token, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( ISashimiPlateController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token).safeTransfer( ISashimiPlateController(controller).treasury(), IERC20(token).balanceOf(address(this)) ); } // We want to get back UNI ETH/token LP tokens uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Performance fee IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _want.mul(performanceFee).div(performanceMax) ); deposit(); } } // Emergency proxy pattern function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swap( address _from, address _to, uint256 _amount ) internal { // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } IUniswapV2Router02(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } }
Withdraw partial funds, normally used with a plate withdrawal
function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(devFundFee).div(devFundMax); IERC20(want).safeTransfer(ISashimiPlateController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(treasuryFee).div(treasuryMax); IERC20(want).safeTransfer( ISashimiPlateController(controller).treasury(), _feeTreasury ); address _plate = ISashimiPlateController(controller).plates(address(want)); IERC20(want).safeTransfer(_plate, _amount.sub(_feeDev).sub(_feeTreasury)); }
1,967,271
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.6.8; import "./ProtoBufRuntime.sol"; import "./GoogleProtobufAny.sol"; library ExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; InnerOp.Data[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new InnerOp.Data[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.path[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); for(uint256 i4 = 0; i4 < input.path.length; i4++) { output.path.push(input.path[i4]); } } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ExistenceProof library NonExistenceProof { //struct definition struct Data { bytes key; ExistenceProof.Data left; ExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; ExistenceProof.store(input.left, output.left); ExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library NonExistenceProof library CommitmentProof { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; BatchProof.Data batch; CompressedBatchProof.Data compressed; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_batch(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_compressed(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_batch( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchProof.Data memory x, uint256 sz) = _decode_BatchProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.batch = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_compressed( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchProof.Data memory x, uint256 sz) = _decode_CompressedBatchProof(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.compressed = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchProof(uint256 p, bytes memory bs) internal pure returns (BatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchProof.Data memory r, ) = BatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchProof(uint256 p, bytes memory bs) internal pure returns (CompressedBatchProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchProof.Data memory r, ) = CompressedBatchProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += BatchProof._encode_nested(r.batch, pointer, bs); pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedBatchProof._encode_nested(r.compressed, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); e += 1 + ProtoBufRuntime._sz_lendelim(BatchProof._estimate(r.batch)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchProof._estimate(r.compressed)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); BatchProof.store(input.batch, output.batch); CompressedBatchProof.store(input.compressed, output.compressed); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CommitmentProof library LeafOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_key; PROOFS_PROTO_GLOBAL_ENUMS.HashOp prehash_value; PROOFS_PROTO_GLOBAL_ENUMS.LengthOp length; bytes prefix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[6] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prehash_key(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_prehash_value(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_prefix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_key( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[2] += 1; } else { r.prehash_key = x; if(counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prehash_value( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[3] += 1; } else { r.prehash_value = x; if(counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_length( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.LengthOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_LengthOp(tmp); if (isNil(r)) { counters[4] += 1; } else { r.length = x; if(counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[6] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.prefix = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (uint(r.prehash_key) != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_key = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_key, pointer, bs); } if (uint(r.prehash_value) != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_prehash_value = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value); pointer += ProtoBufRuntime._encode_enum(_enum_prehash_value, pointer, bs); } if (uint(r.length) != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_length = PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length); pointer += ProtoBufRuntime._encode_enum(_enum_length, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_key)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.prehash_value)); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_LengthOp(r.length)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (uint(r.prehash_key) != 0) { return false; } if (uint(r.prehash_value) != 0) { return false; } if (uint(r.length) != 0) { return false; } if (r.prefix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prehash_key = input.prehash_key; output.prehash_value = input.prehash_value; output.length = input.length; output.prefix = input.prefix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library LeafOp library InnerOp { //struct definition struct Data { PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; bytes prefix; bytes suffix; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_hash(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_prefix(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_suffix(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[1] += 1; } else { r.hash = x; if(counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_prefix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.prefix = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_suffix( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.suffix = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } if (r.prefix.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.prefix, pointer, bs); } if (r.suffix.length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.suffix, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); e += 1 + ProtoBufRuntime._sz_lendelim(r.prefix.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.suffix.length); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (uint(r.hash) != 0) { return false; } if (r.prefix.length != 0) { return false; } if (r.suffix.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.hash = input.hash; output.prefix = input.prefix; output.suffix = input.suffix; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerOp library ProofSpec { //struct definition struct Data { LeafOp.Data leaf_spec; InnerSpec.Data inner_spec; int32 max_depth; int32 min_depth; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_leaf_spec(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_inner_spec(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_max_depth(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_min_depth(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.leaf_spec = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_inner_spec( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerSpec.Data memory x, uint256 sz) = _decode_InnerSpec(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.inner_spec = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.max_depth = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_depth( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.min_depth = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerSpec(uint256 p, bytes memory bs) internal pure returns (InnerSpec.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerSpec.Data memory r, ) = InnerSpec._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf_spec, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += InnerSpec._encode_nested(r.inner_spec, pointer, bs); if (r.max_depth != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_depth, pointer, bs); } if (r.min_depth != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_depth, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf_spec)); e += 1 + ProtoBufRuntime._sz_lendelim(InnerSpec._estimate(r.inner_spec)); e += 1 + ProtoBufRuntime._sz_int32(r.max_depth); e += 1 + ProtoBufRuntime._sz_int32(r.min_depth); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.max_depth != 0) { return false; } if (r.min_depth != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { LeafOp.store(input.leaf_spec, output.leaf_spec); InnerSpec.store(input.inner_spec, output.inner_spec); output.max_depth = input.max_depth; output.min_depth = input.min_depth; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library ProofSpec library InnerSpec { //struct definition struct Data { int32[] child_order; int32 child_size; int32 min_prefix_length; int32 max_prefix_length; bytes empty_child; PROOFS_PROTO_GLOBAL_ENUMS.HashOp hash; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[7] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, r, counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, r, counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.child_order = new int32[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_child_order(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_child_size(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_min_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_max_prefix_length(pointer, bs, nil(), counters); } else if (fieldId == 5) { pointer += _read_empty_child(pointer, bs, nil(), counters); } else if (fieldId == 6) { pointer += _read_hash(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_order( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.child_order[r.child_order.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_child_size( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.child_size = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_min_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.min_prefix_length = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_max_prefix_length( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.max_prefix_length = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_empty_child( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[5] += 1; } else { r.empty_child = x; if (counters[5] > 0) counters[5] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_hash( uint256 p, bytes memory bs, Data memory r, uint[7] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int64 tmp, uint256 sz) = ProtoBufRuntime._decode_enum(p, bs); PROOFS_PROTO_GLOBAL_ENUMS.HashOp x = PROOFS_PROTO_GLOBAL_ENUMS.decode_HashOp(tmp); if (isNil(r)) { counters[6] += 1; } else { r.hash = x; if(counters[6] > 0) counters[6] -= 1; } return sz; } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.child_order.length != 0) { for(i = 0; i < r.child_order.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.child_order[i], pointer, bs); } } if (r.child_size != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.child_size, pointer, bs); } if (r.min_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.min_prefix_length, pointer, bs); } if (r.max_prefix_length != 0) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs ); pointer += ProtoBufRuntime._encode_int32(r.max_prefix_length, pointer, bs); } if (r.empty_child.length != 0) { pointer += ProtoBufRuntime._encode_key( 5, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.empty_child, pointer, bs); } if (uint(r.hash) != 0) { pointer += ProtoBufRuntime._encode_key( 6, ProtoBufRuntime.WireType.Varint, pointer, bs ); int32 _enum_hash = PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash); pointer += ProtoBufRuntime._encode_enum(_enum_hash, pointer, bs); } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.child_order.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.child_order[i]); } e += 1 + ProtoBufRuntime._sz_int32(r.child_size); e += 1 + ProtoBufRuntime._sz_int32(r.min_prefix_length); e += 1 + ProtoBufRuntime._sz_int32(r.max_prefix_length); e += 1 + ProtoBufRuntime._sz_lendelim(r.empty_child.length); e += 1 + ProtoBufRuntime._sz_enum(PROOFS_PROTO_GLOBAL_ENUMS.encode_HashOp(r.hash)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.child_order.length != 0) { return false; } if (r.child_size != 0) { return false; } if (r.min_prefix_length != 0) { return false; } if (r.max_prefix_length != 0) { return false; } if (r.empty_child.length != 0) { return false; } if (uint(r.hash) != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.child_order = input.child_order; output.child_size = input.child_size; output.min_prefix_length = input.min_prefix_length; output.max_prefix_length = input.max_prefix_length; output.empty_child = input.empty_child; output.hash = input.hash; } //array helpers for ChildOrder /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addChildOrder(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.child_order.length + 1); for (uint256 i = 0; i < self.child_order.length; i++) { tmp[i] = self.child_order[i]; } tmp[self.child_order.length] = value; self.child_order = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library InnerSpec library BatchProof { //struct definition struct Data { BatchEntry.Data[] entries; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[2] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new BatchEntry.Data[](counters[1]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[2] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (BatchEntry.Data memory x, uint256 sz) = _decode_BatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_BatchEntry(uint256 p, bytes memory bs) internal pure returns (BatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (BatchEntry.Data memory r, ) = BatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += BatchEntry._encode_nested(r.entries[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(BatchEntry._estimate(r.entries[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, BatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ BatchEntry.Data[] memory tmp = new BatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchProof library BatchEntry { //struct definition struct Data { ExistenceProof.Data exist; NonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (ExistenceProof.Data memory x, uint256 sz) = _decode_ExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (NonExistenceProof.Data memory x, uint256 sz) = _decode_NonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_ExistenceProof(uint256 p, bytes memory bs) internal pure returns (ExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (ExistenceProof.Data memory r, ) = ExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_NonExistenceProof(uint256 p, bytes memory bs) internal pure returns (NonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (NonExistenceProof.Data memory r, ) = NonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += NonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(ExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(NonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library BatchEntry library CompressedBatchProof { //struct definition struct Data { CompressedBatchEntry.Data[] entries; InnerOp.Data[] lookup_inners; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.entries = new CompressedBatchEntry.Data[](counters[1]); r.lookup_inners = new InnerOp.Data[](counters[2]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_entries(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_lookup_inners(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_entries( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedBatchEntry.Data memory x, uint256 sz) = _decode_CompressedBatchEntry(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.entries[r.entries.length - counters[1]] = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_lookup_inners( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (InnerOp.Data memory x, uint256 sz) = _decode_InnerOp(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.lookup_inners[r.lookup_inners.length - counters[2]] = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedBatchEntry(uint256 p, bytes memory bs) internal pure returns (CompressedBatchEntry.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedBatchEntry.Data memory r, ) = CompressedBatchEntry._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_InnerOp(uint256 p, bytes memory bs) internal pure returns (InnerOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (InnerOp.Data memory r, ) = InnerOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.entries.length != 0) { for(i = 0; i < r.entries.length; i++) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += CompressedBatchEntry._encode_nested(r.entries[i], pointer, bs); } } if (r.lookup_inners.length != 0) { for(i = 0; i < r.lookup_inners.length; i++) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs) ; pointer += InnerOp._encode_nested(r.lookup_inners[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; for(i = 0; i < r.entries.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(CompressedBatchEntry._estimate(r.entries[i])); } for(i = 0; i < r.lookup_inners.length; i++) { e += 1 + ProtoBufRuntime._sz_lendelim(InnerOp._estimate(r.lookup_inners[i])); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.entries.length != 0) { return false; } if (r.lookup_inners.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { for(uint256 i1 = 0; i1 < input.entries.length; i1++) { output.entries.push(input.entries[i1]); } for(uint256 i2 = 0; i2 < input.lookup_inners.length; i2++) { output.lookup_inners.push(input.lookup_inners[i2]); } } //array helpers for Entries /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addEntries(Data memory self, CompressedBatchEntry.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ CompressedBatchEntry.Data[] memory tmp = new CompressedBatchEntry.Data[](self.entries.length + 1); for (uint256 i = 0; i < self.entries.length; i++) { tmp[i] = self.entries[i]; } tmp[self.entries.length] = value; self.entries = tmp; } //array helpers for LookupInners /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addLookupInners(Data memory self, InnerOp.Data memory value) internal pure { /** * First resize the array. Then add the new element to the end. */ InnerOp.Data[] memory tmp = new InnerOp.Data[](self.lookup_inners.length + 1); for (uint256 i = 0; i < self.lookup_inners.length; i++) { tmp[i] = self.lookup_inners[i]; } tmp[self.lookup_inners.length] = value; self.lookup_inners = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchProof library CompressedBatchEntry { //struct definition struct Data { CompressedExistenceProof.Data exist; CompressedNonExistenceProof.Data nonexist; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[3] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_exist(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_nonexist(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_exist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.exist = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_nonexist( uint256 p, bytes memory bs, Data memory r, uint[3] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedNonExistenceProof.Data memory x, uint256 sz) = _decode_CompressedNonExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.nonexist = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedNonExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedNonExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedNonExistenceProof.Data memory r, ) = CompressedNonExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.exist, pointer, bs); pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedNonExistenceProof._encode_nested(r.nonexist, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.exist)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedNonExistenceProof._estimate(r.nonexist)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { CompressedExistenceProof.store(input.exist, output.exist); CompressedNonExistenceProof.store(input.nonexist, output.nonexist); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedBatchEntry library CompressedExistenceProof { //struct definition struct Data { bytes key; bytes value; LeafOp.Data leaf; int32[] path; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[5] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, r, counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, nil(), counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } pointer = offset; r.path = new int32[](counters[4]); while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, nil(), counters); } else if (fieldId == 2) { pointer += _read_value(pointer, bs, nil(), counters); } else if (fieldId == 3) { pointer += _read_leaf(pointer, bs, nil(), counters); } else if (fieldId == 4) { pointer += _read_path(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_value( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.value = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_leaf( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (LeafOp.Data memory x, uint256 sz) = _decode_LeafOp(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.leaf = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_path( uint256 p, bytes memory bs, Data memory r, uint[5] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (int32 x, uint256 sz) = ProtoBufRuntime._decode_int32(p, bs); if (isNil(r)) { counters[4] += 1; } else { r.path[r.path.length - counters[4]] = x; if (counters[4] > 0) counters[4] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_LeafOp(uint256 p, bytes memory bs) internal pure returns (LeafOp.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (LeafOp.Data memory r, ) = LeafOp._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; uint256 i; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } if (r.value.length != 0) { pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.value, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += LeafOp._encode_nested(r.leaf, pointer, bs); if (r.path.length != 0) { for(i = 0; i < r.path.length; i++) { pointer += ProtoBufRuntime._encode_key( 4, ProtoBufRuntime.WireType.Varint, pointer, bs) ; pointer += ProtoBufRuntime._encode_int32(r.path[i], pointer, bs); } } return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e;uint256 i; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(r.value.length); e += 1 + ProtoBufRuntime._sz_lendelim(LeafOp._estimate(r.leaf)); for(i = 0; i < r.path.length; i++) { e += 1 + ProtoBufRuntime._sz_int32(r.path[i]); } return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } if (r.value.length != 0) { return false; } if (r.path.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; output.value = input.value; LeafOp.store(input.leaf, output.leaf); output.path = input.path; } //array helpers for Path /** * @dev Add value to an array * @param self The in-memory struct * @param value The value to add */ function addPath(Data memory self, int32 value) internal pure { /** * First resize the array. Then add the new element to the end. */ int32[] memory tmp = new int32[](self.path.length + 1); for (uint256 i = 0; i < self.path.length; i++) { tmp[i] = self.path[i]; } tmp[self.path.length] = value; self.path = tmp; } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedExistenceProof library CompressedNonExistenceProof { //struct definition struct Data { bytes key; CompressedExistenceProof.Data left; CompressedExistenceProof.Data right; } // Decoder section /** * @dev The main decoder for memory * @param bs The bytes array to be decoded * @return The decoded struct */ function decode(bytes memory bs) internal pure returns (Data memory) { (Data memory x, ) = _decode(32, bs, bs.length); return x; } /** * @dev The main decoder for storage * @param self The in-storage struct * @param bs The bytes array to be decoded */ function decode(Data storage self, bytes memory bs) internal { (Data memory x, ) = _decode(32, bs, bs.length); store(x, self); } // inner decoder /** * @dev The decoder for internal usage * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param sz The number of bytes expected * @return The decoded struct * @return The number of bytes decoded */ function _decode(uint256 p, bytes memory bs, uint256 sz) internal pure returns (Data memory, uint) { Data memory r; uint[4] memory counters; uint256 fieldId; ProtoBufRuntime.WireType wireType; uint256 bytesRead; uint256 offset = p; uint256 pointer = p; while (pointer < offset + sz) { (fieldId, wireType, bytesRead) = ProtoBufRuntime._decode_key(pointer, bs); pointer += bytesRead; if (fieldId == 1) { pointer += _read_key(pointer, bs, r, counters); } else if (fieldId == 2) { pointer += _read_left(pointer, bs, r, counters); } else if (fieldId == 3) { pointer += _read_right(pointer, bs, r, counters); } else { if (wireType == ProtoBufRuntime.WireType.Fixed64) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed64(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Fixed32) { uint256 size; (, size) = ProtoBufRuntime._decode_fixed32(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.Varint) { uint256 size; (, size) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += size; } if (wireType == ProtoBufRuntime.WireType.LengthDelim) { uint256 size; (, size) = ProtoBufRuntime._decode_lendelim(pointer, bs); pointer += size; } } } return (r, sz); } // field readers /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_key( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (bytes memory x, uint256 sz) = ProtoBufRuntime._decode_bytes(p, bs); if (isNil(r)) { counters[1] += 1; } else { r.key = x; if (counters[1] > 0) counters[1] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_left( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[2] += 1; } else { r.left = x; if (counters[2] > 0) counters[2] -= 1; } return sz; } /** * @dev The decoder for reading a field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @param r The in-memory struct * @param counters The counters for repeated fields * @return The number of bytes decoded */ function _read_right( uint256 p, bytes memory bs, Data memory r, uint[4] memory counters ) internal pure returns (uint) { /** * if `r` is NULL, then only counting the number of fields. */ (CompressedExistenceProof.Data memory x, uint256 sz) = _decode_CompressedExistenceProof(p, bs); if (isNil(r)) { counters[3] += 1; } else { r.right = x; if (counters[3] > 0) counters[3] -= 1; } return sz; } // struct decoder /** * @dev The decoder for reading a inner struct field * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The decoded inner-struct * @return The number of bytes used to decode */ function _decode_CompressedExistenceProof(uint256 p, bytes memory bs) internal pure returns (CompressedExistenceProof.Data memory, uint) { uint256 pointer = p; (uint256 sz, uint256 bytesRead) = ProtoBufRuntime._decode_varint(pointer, bs); pointer += bytesRead; (CompressedExistenceProof.Data memory r, ) = CompressedExistenceProof._decode(pointer, bs, sz); return (r, sz + bytesRead); } // Encoder section /** * @dev The main encoder for memory * @param r The struct to be encoded * @return The encoded byte array */ function encode(Data memory r) internal pure returns (bytes memory) { bytes memory bs = new bytes(_estimate(r)); uint256 sz = _encode(r, 32, bs); assembly { mstore(bs, sz) } return bs; } // inner encoder /** * @dev The encoder for internal usage * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { uint256 offset = p; uint256 pointer = p; if (r.key.length != 0) { pointer += ProtoBufRuntime._encode_key( 1, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += ProtoBufRuntime._encode_bytes(r.key, pointer, bs); } pointer += ProtoBufRuntime._encode_key( 2, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.left, pointer, bs); pointer += ProtoBufRuntime._encode_key( 3, ProtoBufRuntime.WireType.LengthDelim, pointer, bs ); pointer += CompressedExistenceProof._encode_nested(r.right, pointer, bs); return pointer - offset; } // nested encoder /** * @dev The encoder for inner struct * @param r The struct to be encoded * @param p The offset of bytes array to start decode * @param bs The bytes array to be decoded * @return The number of bytes encoded */ function _encode_nested(Data memory r, uint256 p, bytes memory bs) internal pure returns (uint) { /** * First encoded `r` into a temporary array, and encode the actual size used. * Then copy the temporary array into `bs`. */ uint256 offset = p; uint256 pointer = p; bytes memory tmp = new bytes(_estimate(r)); uint256 tmpAddr = ProtoBufRuntime.getMemoryAddress(tmp); uint256 bsAddr = ProtoBufRuntime.getMemoryAddress(bs); uint256 size = _encode(r, 32, tmp); pointer += ProtoBufRuntime._encode_varint(size, pointer, bs); ProtoBufRuntime.copyBytes(tmpAddr + 32, bsAddr + pointer, size); pointer += size; delete tmp; return pointer - offset; } // estimator /** * @dev The estimator for a struct * @param r The struct to be encoded * @return The number of bytes encoded in estimation */ function _estimate( Data memory r ) internal pure returns (uint) { uint256 e; e += 1 + ProtoBufRuntime._sz_lendelim(r.key.length); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.left)); e += 1 + ProtoBufRuntime._sz_lendelim(CompressedExistenceProof._estimate(r.right)); return e; } // empty checker function _empty( Data memory r ) internal pure returns (bool) { if (r.key.length != 0) { return false; } return true; } //store function /** * @dev Store in-memory struct to storage * @param input The in-memory struct * @param output The in-storage struct */ function store(Data memory input, Data storage output) internal { output.key = input.key; CompressedExistenceProof.store(input.left, output.left); CompressedExistenceProof.store(input.right, output.right); } //utility functions /** * @dev Return an empty struct * @return r The empty struct */ function nil() internal pure returns (Data memory r) { assembly { r := 0 } } /** * @dev Test whether a struct is empty * @param x The struct to be tested * @return r True if it is empty */ function isNil(Data memory x) internal pure returns (bool r) { assembly { r := iszero(x) } } } //library CompressedNonExistenceProof library PROOFS_PROTO_GLOBAL_ENUMS { //enum definition // Solidity enum definitions enum HashOp { NO_HASH, SHA256, SHA512, KECCAK, RIPEMD160, BITCOIN } // Solidity enum encoder function encode_HashOp(HashOp x) internal pure returns (int32) { if (x == HashOp.NO_HASH) { return 0; } if (x == HashOp.SHA256) { return 1; } if (x == HashOp.SHA512) { return 2; } if (x == HashOp.KECCAK) { return 3; } if (x == HashOp.RIPEMD160) { return 4; } if (x == HashOp.BITCOIN) { return 5; } revert(); } // Solidity enum decoder function decode_HashOp(int64 x) internal pure returns (HashOp) { if (x == 0) { return HashOp.NO_HASH; } if (x == 1) { return HashOp.SHA256; } if (x == 2) { return HashOp.SHA512; } if (x == 3) { return HashOp.KECCAK; } if (x == 4) { return HashOp.RIPEMD160; } if (x == 5) { return HashOp.BITCOIN; } revert(); } // Solidity enum definitions enum LengthOp { NO_PREFIX, VAR_PROTO, VAR_RLP, FIXED32_BIG, FIXED32_LITTLE, FIXED64_BIG, FIXED64_LITTLE, REQUIRE_32_BYTES, REQUIRE_64_BYTES } // Solidity enum encoder function encode_LengthOp(LengthOp x) internal pure returns (int32) { if (x == LengthOp.NO_PREFIX) { return 0; } if (x == LengthOp.VAR_PROTO) { return 1; } if (x == LengthOp.VAR_RLP) { return 2; } if (x == LengthOp.FIXED32_BIG) { return 3; } if (x == LengthOp.FIXED32_LITTLE) { return 4; } if (x == LengthOp.FIXED64_BIG) { return 5; } if (x == LengthOp.FIXED64_LITTLE) { return 6; } if (x == LengthOp.REQUIRE_32_BYTES) { return 7; } if (x == LengthOp.REQUIRE_64_BYTES) { return 8; } revert(); } // Solidity enum decoder function decode_LengthOp(int64 x) internal pure returns (LengthOp) { if (x == 0) { return LengthOp.NO_PREFIX; } if (x == 1) { return LengthOp.VAR_PROTO; } if (x == 2) { return LengthOp.VAR_RLP; } if (x == 3) { return LengthOp.FIXED32_BIG; } if (x == 4) { return LengthOp.FIXED32_LITTLE; } if (x == 5) { return LengthOp.FIXED64_BIG; } if (x == 6) { return LengthOp.FIXED64_LITTLE; } if (x == 7) { return LengthOp.REQUIRE_32_BYTES; } if (x == 8) { return LengthOp.REQUIRE_64_BYTES; } revert(); } } //library PROOFS_PROTO_GLOBAL_ENUMS
store function Store in-memory struct to storage input The in-memory struct output The in-storage struct/
function store(Data memory input, Data storage output) internal { ExistenceProof.store(input.exist, output.exist); NonExistenceProof.store(input.nonexist, output.nonexist); BatchProof.store(input.batch, output.batch); CompressedBatchProof.store(input.compressed, output.compressed); }
13,050,193
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // Interfaces import "@openzeppelin/contracts/governance/IGovernor.sol"; // Libraries import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/Timers.sol"; import {LibGovernor} from "../libraries/LibGovernor.sol"; import {LibERC721} from "../libraries/LibERC721.sol"; import {LibDiamond} from "../libraries/LibDiamond.sol"; // Contracts import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; import "@openzeppelin/contracts/governance/TimelockController.sol"; import "../utils/Modifiers.sol"; /** * @dev Core of the governance system, designed to be extended though various modules. * * This contract is abstract and requires several function to be implemented in various modules: * * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote} * - A voting module must implement {getVotes} * - Additionanly, the {votingPeriod} must also be implemented */ contract GovernorFacet is EIP712, Modifiers { using SafeCast for uint256; using Timers for Timers.BlockNumber; /** * @dev Sets the value for {name} and {version} */ constructor() EIP712("NffeelsGovernor", "1") {} /** * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function governorName() public view returns (string memory) { return LibGovernor.governorStorage().name; } /** * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function governorVersion() public pure returns (string memory) { return "1"; } /** * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = For, 1 = Against, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ function COUNTING_MODE() public pure returns (string memory) { return "support=bravo&quorum=for,abstain"; } /** * @dev delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public pure returns (uint256) { return 1; // 1 block } /** * @dev delay, in number of blocks, between the vote start and vote ends. * * Note: the {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public pure returns (uint256) { return 45818; // 1 week } /** * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view returns (uint256) { return LibGovernor.quorum(blockNumber); } /** * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. */ function proposalThreshold() public pure returns (uint256) { return 1; } /** * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view returns (uint256) { return LibGovernor.getVotes(account, blockNumber); } /** * @dev See {LibGovernor-hashProposal}. * * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * accross multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public pure returns (uint256) { return LibGovernor.hashProposal( targets, values, calldatas, descriptionHash ); } /** * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view returns (LibGovernor.ProposalState) { return LibGovernor.state(proposalId); } /** * @dev block number used to retrieve user's votes and quorum. */ function proposalSnapshot(uint256 proposalId) public view returns (uint256) { return LibGovernor.proposalSnapshot(proposalId); } /** * @dev timestamp at which votes close. */ function proposalDeadline(uint256 proposalId) public view returns (uint256) { return LibGovernor .governorStorage() .proposals[proposalId] .voteEnd .getDeadline(); } /** * @dev Create a new proposal. Vote start {LibGovernor-votingDelay} blocks after the proposal is created and ends * {LibGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public returns (uint256) { require( getVotes(address(msg.sender), block.number - 1) >= proposalThreshold(), "Governor: proposer votes below proposal threshold" ); uint256 proposalId = LibGovernor.hashProposal( targets, values, calldatas, keccak256(bytes(description)) ); require( targets.length == values.length, "Governor: invalid proposal length" ); require( targets.length == calldatas.length, "Governor: invalid proposal length" ); require(targets.length > 0, "Governor: empty proposal"); LibGovernor.ProposalCore storage proposal = LibGovernor .governorStorage() .proposals[proposalId]; require( proposal.voteStart.isUnset(), "Governor: proposal already exists" ); uint64 snapshot = block.number.toUint64() + votingDelay().toUint64(); uint64 deadline = snapshot + votingPeriod().toUint64(); proposal.voteStart.setDeadline(snapshot); proposal.voteEnd.setDeadline(deadline); emit LibGovernor.ProposalCreated( proposalId, address(msg.sender), targets, values, new string[](targets.length), calldatas, snapshot, deadline, description ); return proposalId; } /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable returns (uint256) { uint256 proposalId = LibGovernor.hashProposal( targets, values, calldatas, descriptionHash ); LibGovernor.ProposalState status = state(proposalId); require( status == LibGovernor.ProposalState.Succeeded || status == LibGovernor.ProposalState.Queued, "Governor: proposal not successful" ); LibGovernor.governorStorage().proposals[proposalId].executed = true; emit LibGovernor.ProposalExecuted(proposalId); LibGovernor.execute( proposalId, targets, values, calldatas, descriptionHash ); return proposalId; } /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public returns (uint256) { address voter = address(msg.sender); return LibGovernor.castVote(proposalId, voter, support, ""); } /** * @dev Cast a with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public returns (uint256) { address voter = address(msg.sender); return LibGovernor.castVote(proposalId, voter, support, reason); } /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public returns (uint256) { address voter = ECDSA.recover( _hashTypedDataV4( keccak256( abi.encode(LibGovernor.BALLOT_TYPEHASH, proposalId, support) ) ), v, r, s ); return LibGovernor.castVote(proposalId, voter, support, ""); } /** * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view returns (bool) { return LibGovernor.governorStorage().proposalVotes[proposalId].hasVoted[ account ]; } /** * @dev Accessor to the internal vote counts. */ function proposalVotes(uint256 proposalId) public view returns ( uint256 againstVotes, uint256 forVotes, uint256 abstainVotes ) { LibGovernor.ProposalVote storage proposalvote = LibGovernor .governorStorage() .proposalVotes[proposalId]; return ( proposalvote.againstVotes, proposalvote.forVotes, proposalvote.abstainVotes ); } /* GovernorTimelockControl */ /** * @dev Public accessor to check the address of the timelock */ function timelock() public view returns (address) { return address(LibGovernor.governorStorage().timelock); } /** * @dev Public accessor to check the eta of a queued proposal */ function proposalEta(uint256 proposalId) public view returns (uint256) { uint256 eta = LibGovernor.governorStorage().timelock.getTimestamp( LibGovernor.governorStorage().timelockIds[proposalId] ); return eta == 1 ? 0 : eta; // _DONE_TIMESTAMP (1) should be replaced with a 0 value } /** * @dev Function to queue a proposal to the timelock. */ function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public returns (uint256) { return LibGovernor.queue(targets, values, calldatas, descriptionHash); } /** * @dev Public endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates * must be proposed, scheduled and executed using the {Governor} workflow. */ function updateTimelock(TimelockController newTimelock) external onlyGovernance { LibGovernor.updateTimelock(newTimelock); } /* GovernorVotesQuorumFraction */ /** * @dev Returns the quorum numerator value. */ function quorumNumerator() public view returns (uint256) { return LibGovernor.governorStorage().quorumNumerator; } /** * @dev Returns the quorum denominator value. */ function quorumDenominator() public pure returns (uint256) { return LibGovernor.QUORUM_DENOMINATOR; } /** * @dev Update quorumNumerator. */ function updateQuorumNumerator(uint256 newQuorumNumerator) external onlyGovernance { LibGovernor.updateQuorumNumerator(newQuorumNumerator); } }
Cast a vote Emits a {VoteCast} event./
function castVote(uint256 proposalId, uint8 support) public returns (uint256) { address voter = address(msg.sender); return LibGovernor.castVote(proposalId, voter, support, ""); }
1,795,170
/* ███████╗ █████╗ ██╗ ██████╗ ██████╗ ███╗ ██╗ ██╗ ██╗ ██╔════╝██╔══██╗██║ ██╔════╝██╔═══██╗████╗ ██║ ╚██╗██╔╝ █████╗ ███████║██║ ██║ ██║ ██║██╔██╗ ██║ ╚███╔╝ ██╔══╝ ██╔══██║██║ ██║ ██║ ██║██║╚██╗██║ ██╔██╗ ██║ ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║ ██╔╝ ██╗ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ projectfalconx.com 2.5% Auto LP 4% Marketing 1.5% team 0% Referral and Community */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } abstract contract IERC20Extented is IERC20 { function decimals() external view virtual returns (uint8); function name() external view virtual returns (string memory); function symbol() external view virtual returns (string memory); } contract FalconX is Context, IERC20, IERC20Extented, Ownable { using SafeMath for uint256; string private constant _name = "FalconX"; string private constant _symbol = "FALCX"; uint8 private constant _decimals = 9; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant _tTotal = 600000000000 * 10**9; // 600 Billion uint256 public _priceImpact = 2; uint256 private _firstBlock; uint256 private _botBlocks; uint256 public _maxWalletAmount; uint256 private _maxSellAmountBNB = 5000000000000000000; // 5 BNB uint256 private _minBuyBNB = 0; //10000000000000000; // 0.01 BNB uint256 private _minSellBNB = 0; //10000000000000000; // 0.01 BNB // fees uint256 public _liquidityFee = 25; // divided by 1000 uint256 private _previousLiquidityFee = _liquidityFee; uint256 public _marketingFee = 40; // divided by 1000 uint256 private _previousMarketingFee = _marketingFee; uint256 public _teamFee = 15; // divided by 1000 uint256 private _previousTeamFee = _teamFee; uint256 public _communityFee = 0 ;// divided by 1000 uint256 private _previousCommunityFee = _communityFee; uint256 public _burnFee = 0; // divided by 1000 uint256 private _previousBurnFee = _burnFee; uint256 private _marketingPercent = 73; uint256 private _teamPercent = 27; uint256 private _communityPercent = 0; struct FeeBreakdown { uint256 tLiquidity; uint256 tMarketing; uint256 tTeam; uint256 tCommunity; uint256 tBurn; uint256 tAmount; } mapping(address => bool) private bots; address payable private _marketingAddress = payable(0xA5347334AF09Bbc6C2456AB435F54ef8189FA709); address payable private _teamAddress = payable(0x5cCaA2b9f967019FE5ea59AC572407dBe0858cbE); address payable private _communityAddress = payable(0xBD92de26245518A172732222749e662Fb28b4674); address payable constant private _burnAddress = payable(0x000000000000000000000000000000000000dEaD); address private presaleRouter; address private presaleAddress; IUniswapV2Router02 private uniswapV2Router; address public uniswapV2Pair; uint256 private _maxTxAmount; bool private tradingOpen = false; bool private inSwap = false; bool private presale = true; bool private pairSwapped = false; bool public _priceImpactSellLimitEnabled = false; bool public _BNBsellLimitEnabled = false; address public bridge; event EndedPresale(bool presale); event MaxTxAmountUpdated(uint256 _maxTxAmount); event PercentsUpdated(uint256 _marketingPercent, uint256 _teamPercent, uint256 _communityPercent); event FeesUpdated(uint256 _marketingFee, uint256 _liquidityFee, uint256 _teamFee, uint256 _communityFee, uint256 _burnFee); event PriceImpactUpdated(uint256 _priceImpact); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor(address _bridge) { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);//ropstenn 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //bsc test 0xD99D1c33F9fC3444f8101754aBC46c52416550D1);//bsc main net 0x10ED43C718714eb63d5aA57B78B54704E256024E); uniswapV2Router = _uniswapV2Router; _approve(address(this), address(uniswapV2Router), _tTotal); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); IERC20(uniswapV2Pair).approve(address(uniswapV2Router),type(uint256).max); _maxTxAmount = _tTotal; // start off transaction limit at 100% of total supply _maxWalletAmount = _tTotal.div(1); // 100% _priceImpact = 100; _balances[_bridge] = _tTotal; bridge = _bridge; _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() override external pure returns (string memory) { return _name; } function symbol() override external pure returns (string memory) { return _symbol; } function decimals() override external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function isBot(address account) public view returns (bool) { return bots[account]; } function setBridge(address _bridge) external onlyOwner { bridge = _bridge; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); _approve(sender,_msgSender(),_allowances[sender][_msgSender()].sub(amount,"ERC20: transfer amount exceeds allowance")); return true; } function removeAllFee() private { if (_marketingFee == 0 && _liquidityFee == 0 && _teamFee == 0 && _communityFee == 0 && _burnFee == 0) return; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTeamFee = _teamFee; _previousCommunityFee = _communityFee; _previousBurnFee = _burnFee; _marketingFee = 0; _liquidityFee = 0; _teamFee = 0; _communityFee = 0; _burnFee = 0; } function setBotFee() private { _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTeamFee = _teamFee; _previousCommunityFee = _communityFee; _previousBurnFee = _burnFee; _marketingFee = 180; _liquidityFee = 180; _teamFee = 18; _communityFee = 18; _burnFee = 180; } function restoreAllFee() private { _marketingFee = _previousMarketingFee; _liquidityFee = _previousLiquidityFee; _teamFee = _previousTeamFee; _communityFee = _previousCommunityFee; _burnFee = _previousBurnFee; } function _approve(address owner, address spender, uint256 amount) private { 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); } // calculate price based on pair reserves function getTokenPriceBNB(uint256 amount) external view returns(uint256) { IERC20Extented token0 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token0());//FalconX IERC20Extented token1 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token1());//bnb require(token0.decimals() != 0, "ERR: decimals cannot be zero"); (uint112 Res0, uint112 Res1,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); if(pairSwapped) { token0 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token1());//FalconX token1 = IERC20Extented(IUniswapV2Pair(uniswapV2Pair).token0());//bnb (Res1, Res0,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); } uint res1 = Res1*(10**token0.decimals()); return((amount*res1)/(Res0*(10**token0.decimals()))); // return amount of token1 needed to buy token0 } function _transfer(address from, address to, uint256 amount) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); bool takeFee = true; if (from != owner() && to != owner() && !presale && from != address(this) && to != address(this) && from != bridge && to != bridge) { require(tradingOpen); if (from != presaleRouter && from != presaleAddress) { require(amount <= _maxTxAmount); } if (from == uniswapV2Pair && to != address(uniswapV2Router)) {//buys if (block.timestamp <= _firstBlock.add(_botBlocks) && from != presaleRouter && from != presaleAddress) { bots[to] = true; } uint256 bnbAmount = this.getTokenPriceBNB(amount); require(bnbAmount >= _minBuyBNB, "you must buy at least min BNB worth of token"); require(balanceOf(to).add(amount) <= _maxWalletAmount, "wallet balance after transfer must be less than max wallet amount"); } if (!inSwap && from != uniswapV2Pair) { //sells, transfers require(!bots[from] && !bots[to]); uint256 bnbAmount = this.getTokenPriceBNB(amount); require(bnbAmount >= _minSellBNB, "you must sell at least the min BNB worth of token"); if (_BNBsellLimitEnabled) { require(bnbAmount <= _maxSellAmountBNB, 'you cannot sell more than the max BNB amount per transaction'); } else if (_priceImpactSellLimitEnabled) { require(amount <= balanceOf(uniswapV2Pair).mul(_priceImpact).div(100)); // price impact limit } if(to != uniswapV2Pair) { require(balanceOf(to).add(amount) <= _maxWalletAmount, "wallet balance after transfer must be less than max wallet amount"); } uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance > 0) { swapAndLiquify(contractTokenBalance); } uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } if (_isExcludedFromFee[from] || _isExcludedFromFee[to] || presale || from == bridge || to == bridge) { takeFee = false; } else if (bots[from] || bots[to]) { setBotFee(); takeFee = true; } if (presale) { require(from == owner() || from == presaleRouter || from == presaleAddress); } _tokenTransfer(from, to, amount, takeFee); restoreAllFee(); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, path, address(this), block.timestamp); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 autoLPamount = _liquidityFee.mul(contractTokenBalance).div(_marketingFee.add(_teamFee).add(_communityFee).add(_liquidityFee)); // split the contract balance into halves uint256 half = autoLPamount.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current BNB balance. // this is so that we can capture exactly the amount of BNB that the // swap creates, and not make the liquidity event include any BNB that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for BNB swapTokensForEth(otherHalf); // <- this breaks the BNB -> HATE swap when swap+liquify is triggered // how much BNB did we just swap into? uint256 newBalance = ((address(this).balance.sub(initialBalance)).mul(half)).div(otherHalf); // add liquidity to pancakeswap addLiquidity(half, newBalance); } function sendETHToFee(uint256 amount) private { _marketingAddress.transfer(amount.mul(_marketingPercent).div(100)); _teamAddress.transfer(amount.mul(_teamPercent).div(100)); _communityAddress.transfer(amount.mul(_communityPercent).div(100)); } function openTrading(uint256 botBlocks) private { _firstBlock = block.timestamp; _botBlocks = botBlocks; tradingOpen = true; } function manualswap() external { require(_msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); if (contractBalance > 0) { swapTokensForEth(contractBalance); } } function manualsend() external { require(_msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(contractETHBalance); } } function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private { if (!takeFee) { removeAllFee(); } _transferStandard(sender, recipient, amount); restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 amount) private { FeeBreakdown memory fees; fees.tMarketing = amount.mul(_marketingFee).div(1000); fees.tLiquidity = amount.mul(_liquidityFee).div(1000); fees.tTeam = amount.mul(_teamFee).div(1000); fees.tCommunity = amount.mul(_communityFee).div(1000); fees.tBurn = amount.mul(_burnFee).div(1000); fees.tAmount = amount.sub(fees.tMarketing).sub(fees.tLiquidity).sub(fees.tTeam).sub(fees.tCommunity).sub(fees.tBurn); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(fees.tAmount); _balances[address(this)] = _balances[address(this)].add(fees.tMarketing.add(fees.tLiquidity).add(fees.tTeam).add(fees.tCommunity)); _balances[_burnAddress] = _balances[_burnAddress].add(fees.tBurn); emit Transfer(sender, recipient, fees.tAmount); } receive() external payable {} function excludeFromFee(address account) public onlyOwner() { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner() { _isExcludedFromFee[account] = false; } function removeBot(address account) external onlyOwner() { bots[account] = false; } function addBot(address account) external onlyOwner() { bots[account] = true; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { require(maxTxAmount > _tTotal.div(10000), "Amount must be greater than 0.01% of supply"); require(maxTxAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxTxAmount = maxTxAmount; emit MaxTxAmountUpdated(_maxTxAmount); } function setMaxWalletAmount(uint256 maxWalletAmount) external onlyOwner() { require(maxWalletAmount > _tTotal.div(200), "Amount must be greater than 0.5% of supply"); require(maxWalletAmount <= _tTotal, "Amount must be less than or equal to totalSupply"); _maxWalletAmount = maxWalletAmount; } function setTaxes(uint256 marketingFee, uint256 liquidityFee, uint256 teamFee, uint256 communityFee, uint256 burnFee) external onlyOwner() { uint256 totalFee = marketingFee.add(liquidityFee).add(teamFee).add(communityFee).add(burnFee); require(totalFee.div(10) < 50, "Sum of fees must be less than 50"); _marketingFee = marketingFee; _liquidityFee = liquidityFee; _teamFee = teamFee; _communityFee = communityFee; _burnFee = burnFee; _previousMarketingFee = _marketingFee; _previousLiquidityFee = _liquidityFee; _previousTeamFee = _teamFee; _previousCommunityFee = _communityFee; _previousBurnFee = _burnFee; uint256 totalBNBfees = _marketingFee.add(_teamFee).add(_communityFee); _marketingPercent = (_marketingFee.mul(100)).div(totalBNBfees); _teamPercent = (_teamFee.mul(100)).div(totalBNBfees); _communityPercent = (_communityFee.mul(100)).div(totalBNBfees); emit FeesUpdated(_marketingFee, _liquidityFee, _teamFee, _communityFee, _burnFee); } function setPriceImpact(uint256 priceImpact) external onlyOwner() { require(priceImpact <= 100, "max price impact must be less than or equal to 100"); require(priceImpact > 0, "cant prevent sells, choose value greater than 0"); _priceImpact = priceImpact; emit PriceImpactUpdated(_priceImpact); } function setPresaleRouterAndAddress(address router, address wallet) external onlyOwner() { presaleRouter = router; presaleAddress = wallet; excludeFromFee(presaleRouter); excludeFromFee(presaleAddress); } function endPresale(uint256 botBlocks) external onlyOwner() { require(presale == true, "presale already ended"); presale = false; openTrading(botBlocks); emit EndedPresale(presale); } function updatePairSwapped(bool swapped) external onlyOwner() { pairSwapped = swapped; } function updateMinBuySellBNB(uint256 minBuyBNB, uint256 minSellBNB) external onlyOwner() { require(minBuyBNB <= 100000000000000000, "cant make the limit higher than 0.1 BNB"); require(minSellBNB <= 100000000000000000, "cant make the limit higher than 0.1 BNB"); _minBuyBNB = minBuyBNB; _minSellBNB = minSellBNB; } function updateMaxSellAmountBNB(uint256 maxSellBNB) external onlyOwner() { require(maxSellBNB >= 1000000000000000000, "cant make the limit lower than 1 BNB"); _maxSellAmountBNB = maxSellBNB; } function updateCommunityAddress(address payable communityAddress) external onlyOwner() { _communityAddress = communityAddress; } function updateMarketingAddress(address payable marketingAddress) external onlyOwner() { _marketingAddress = marketingAddress; } function updateTeamAddress(address payable teamAddress) external onlyOwner() { _teamAddress = teamAddress; } function enableBNBsellLimit() external onlyOwner() { require(_BNBsellLimitEnabled == false, "already enabled"); _BNBsellLimitEnabled = true; _priceImpactSellLimitEnabled = false; } function disableBNBsellLimit() external onlyOwner() { require(_BNBsellLimitEnabled == true, "already disabled"); _BNBsellLimitEnabled = false; } function enablePriceImpactSellLimit() external onlyOwner() { require(_priceImpactSellLimitEnabled == false, "already enabled"); _priceImpactSellLimitEnabled = true; _BNBsellLimitEnabled = false; } function disablePriceImpactSellLimit() external onlyOwner() { require(_priceImpactSellLimitEnabled == true, "already disabled"); _priceImpactSellLimitEnabled = false; } } /* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░██ ░░ ██ ░░ ██ ░░ ██ Spade Secured ██ ░░ ████ ██ ░░ ▒▒▒▒██ ██ ░░ ██▓▓████ ██ ░░ ▓▓▒▒▒▒██ ██ ░░ ▒▒ ██ ██ ░░ ▓▓ ▓▓▒▒ ██ ░░ ██ ░░ ██▒▒ ██████ ██ ░░ ▒▒████ ██████▒▒ ██ ░░ ████████ ▒▒████████ ██ ░░ ████████ ██████████████ ██ ░░ ▒▒ ██████████████████ ██ ░░ ░░ ██████████████████████ ██ ░░ ██████████████████████████ ██ ░░ ████████████████████████████ ██ ░░ ████████████████████████████████ ██ ░░ ████████████████████████████████████ ██ ░░ ▓▓████████████████████████████████████░░ ██ ░░ ████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████ ██ ░░ ████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████▒▒ ██ ░░ ▒▒████████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████████ ██ ░░ ██████████████████████████████████████████████▓▓ ██ ░░ ████████████████▒▒██████ ██████████████████ ██ ░░ ████████████▒▒ ██████ ██████████████ ██ ░░ ░░░░░░░░░░ ██████ ░░░░░░░░░░ ██ ░░ ██████ ██ ░░ ░░████████ ██ ░░ ▒▒████████████ ██ ░░ ▒▒████████████████ ██ ░░ ░░░░░░░░░░░░░░░░░░ ▒▒ ██ ░░ ████▒▒██ ██ ░░ ████████ ██ ░░ ██████ ██ ░░ ████ ██ ░░ ██ ░░ ░░ ░░ ██ ░░ ██ ██ ░░ ████████ ██ ░░ ░░ ██ ██ ░░ ██████ ██ ░░ ▒▒██ ██ ░░ ░░ ██ ░░ ██ ░░ Spadetech.io ██ */
calculate price based on pair reserves
function getTokenPriceBNB(uint256 amount) external view returns(uint256) { require(token0.decimals() != 0, "ERR: decimals cannot be zero"); (uint112 Res0, uint112 Res1,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); if(pairSwapped) { (Res1, Res0,) = IUniswapV2Pair(uniswapV2Pair).getReserves(); } uint res1 = Res1*(10**token0.decimals()); }
10,105,620
/** *Submitted for verification at Etherscan.io on 2021-03-23 */ /** *Submitted for verification at Etherscan.io on 2021-03-01 */ /** *Submitted for verification at Etherscan.io on 2020-10-19 */ pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Select * @dev Median Selection Library */ library Select { using SafeMath for uint256; /** * @dev Sorts the input array up to the denoted size, and returns the median. * @param array Input array to compute its median. * @param size Number of elements in array to compute the median for. * @return Median of array. */ function computeMedian(uint256[] array, uint256 size) internal pure returns (uint256) { require(size > 0 && array.length >= size); for (uint256 i = 1; i < size; i++) { for (uint256 j = i; j > 0 && array[j-1] > array[j]; j--) { uint256 tmp = array[j]; array[j] = array[j-1]; array[j-1] = tmp; } } if (size % 2 == 1) { return array[size / 2]; } else { return array[size / 2].add(array[size / 2 - 1]) / 2; } } } interface IOracle { function getData() external returns (uint256, bool); } /** * @title Median Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract MedianOracle is Ownable, IOracle { using SafeMath for uint256; struct Report { uint256 timestamp; uint256 payload; } // Addresses of providers authorized to push reports. address[] public providers; // Address of the target asset. address public targetAsset; // Reports indexed by provider address. Report[0].timestamp > 0 // indicates provider existence. mapping (address => Report[2]) public providerReports; event ProviderAdded(address provider); event ProviderRemoved(address provider); event ReportTimestampOutOfRange(address provider); event ProviderReportPushed(address indexed provider, uint256 payload, uint256 timestamp); // The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; // The number of seconds since reporting that has to pass before a report // is usable. uint256 public reportDelaySec; // The minimum number of providers with valid reports to consider the // aggregate report valid. uint256 public minimumProviders = 1; // Timestamp of 1 is used to mark uninitialized and invalidated data. // This is needed so that timestamp of 1 is always considered expired. uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks; /** * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. * @param reportDelaySec_ The number of seconds since reporting that has to * pass before a report is usable * @param minimumProviders_ The minimum number of providers with valid * reports to consider the aggregate report valid. */ constructor(uint256 reportExpirationTimeSec_, uint256 reportDelaySec_, uint256 minimumProviders_) public { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); require(minimumProviders_ > 0); reportExpirationTimeSec = reportExpirationTimeSec_; reportDelaySec = reportDelaySec_; minimumProviders = minimumProviders_; } /** * @notice Sets the report expiration period. * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. */ function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_) external onlyOwner { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); reportExpirationTimeSec = reportExpirationTimeSec_; } /** * @notice Sets the time period since reporting that has to pass before a * report is usable. * @param reportDelaySec_ The new delay period in seconds. */ function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner { reportDelaySec = reportDelaySec_; } /** * @notice Sets the minimum number of providers with valid reports to * consider the aggregate report valid. * @param minimumProviders_ The new minimum number of providers. */ function setMinimumProviders(uint256 minimumProviders_) external onlyOwner { require(minimumProviders_ > 0); minimumProviders = minimumProviders_; } /** * @notice Sets the asset contract address to track the price. * @param targetAsset_ Address of the asset token. */ function setTargetAsset( address targetAsset_) external onlyOwner { targetAsset = targetAsset_; } /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external { address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; // Check that the push is not too soon after the last one. require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); } /** * @notice Invalidates the reports of the calling provider. */ function purgeReports() external { address providerAddress = msg.sender; require (providerReports[providerAddress][0].timestamp > 0); providerReports[providerAddress][0].timestamp=1; providerReports[providerAddress][1].timestamp=1; } /** * @notice Computes median of provider reports whose timestamps are in the * valid timestamp range. * @return AggregatedValue: Median of providers reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() external returns (uint256, bool) { uint256 reportsCount = providers.length; uint256[] memory validReports = new uint256[](reportsCount); uint256 size = 0; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { // Recent report is too recent. uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { // Past report is too old. emit ReportTimestampOutOfRange(providerAddress); } else if (reportTimestampPast > maxValidTimestamp) { // Past report is too recent. emit ReportTimestampOutOfRange(providerAddress); } else { // Using past report. validReports[size++] = providerReports[providerAddress][index_past].payload; } } else { // Recent report is not too recent. if (reportTimestampRecent < minValidTimestamp) { // Recent report is too old. emit ReportTimestampOutOfRange(providerAddress); } else { // Using recent report. validReports[size++] = providerReports[providerAddress][index_recent].payload; } } } if (size < minimumProviders) { return (0, false); } return (Select.computeMedian(validReports, size), true); } /** * @notice Authorizes a provider. * @param provider Address of the provider. */ function addProvider(address provider) external onlyOwner { require(providerReports[provider][0].timestamp == 0); providers.push(provider); providerReports[provider][0].timestamp = 1; emit ProviderAdded(provider); } /** * @notice Revokes provider authorization. * @param provider Address of the provider. */ function removeProvider(address provider) external onlyOwner { delete providerReports[provider]; for (uint256 i = 0; i < providers.length; i++) { if (providers[i] == provider) { if (i + 1 != providers.length) { providers[i] = providers[providers.length-1]; } providers.length--; emit ProviderRemoved(provider); break; } } } /** * @return The number of authorized providers. */ function providersSize() external view returns (uint256) { return providers.length; } }
Pushes a report for the calling provider. payload is expected to be 18 decimal fixed point number./ Check that the push is not too soon after the last one.
function pushReport(uint256 payload) external { address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); }
2,249,595
/** *Submitted for verification at Etherscan.io */ /** *Submitted for verification at Etherscan.io */ /* Welcome To Pronitz Total Supply : 1,000,000,000 $NITZ Buy Tax : 10% | Sell Tax : 10% Max TX : 0.25% | Wallet Cap : 1% Join Us Now: Website : https://pronitz.com/ Telegram : https://t.me/pronitz Twitter: https://twitter.com/pronitz */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract Pronitz is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; bool private um = true; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; mapping (address => bool) private bots; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; bool private boughtEarly = true; uint256 private _firstBlock; uint256 private _botBlocks; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event EndedBoughtEarly(bool boughtEarly); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("PRONITZ", "NITZ") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 6; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 12; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 25 / 10000; // 0.25% maxTransactionAmountTxn maxWallet = totalSupply * 10 / 1000; // 1% maxWallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = payable(0x4D7432879648AD91d783898Be711622b406A8DA8); devWallet = payable(0x5253a5DC31b41B51baC9eB2Ac50260a6dB9286a4); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(devWallet), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(marketingWallet), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if (from == uniswapV2Pair && to != address(uniswapV2Router)) { if (block.number <= _firstBlock.add(_botBlocks)) { bots[to] = true; } } require(!bots[from] && !bots[to]); if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setBots(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function openTrading(uint256 botBlocks) private { _firstBlock = block.number; _botBlocks = botBlocks; tradingActive = true; } // once enabled, can never be turned off function enableTrading(uint256 botBlocks) external onlyOwner() { require(botBlocks <= 1, "don't catch humans"); swapEnabled = true; require(boughtEarly == true, "done"); boughtEarly = false; openTrading(botBlocks); emit EndedBoughtEarly(boughtEarly); } }
exclude from paying fees or having max transaction amount
constructor() ERC20("PRONITZ", "NITZ") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 2; uint256 _buyLiquidityFee = 2; uint256 _buyDevFee = 6; uint256 _sellMarketingFee = 2; uint256 _sellLiquidityFee = 4; uint256 _sellDevFee = 12; uint256 totalSupply = 1 * 1e9 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = payable(0x4D7432879648AD91d783898Be711622b406A8DA8); devWallet = payable(0x5253a5DC31b41B51baC9eB2Ac50260a6dB9286a4); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(devWallet), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(marketingWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
6,007,672
./full_match/11155111/0x247f65BD849d686147330978AA7521457c5A83bf/sources/project:/contracts/superfluid/SuperToken.sol
Burn tokens from address token holder address amount uint256 amount of tokens to burn userData bytes extra information provided by the token holder operatorData bytes extra information provided by the operator (if any)/
function _burn( address operator, address from, uint256 amount, bool invokeHook, bytes memory userData, bytes memory operatorData ) internal { if (from == address(0)) { revert SUPER_TOKEN_BURN_FROM_ZERO_ADDRESS(); } if (invokeHook) { _callTokensToSend(operator, from, address(0), amount, userData, operatorData); } SuperfluidToken._burn(from, amount); emit Burned(operator, from, amount, userData, operatorData); emit Transfer(from, address(0), amount); }
3,837,106
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface IERC20 { function TOTALSUPPLY15() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF165(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER42(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE912(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE113(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM313(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER502(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL286(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/P2pSwap.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; contract P2pSwap { struct Swap { address aliceAddress; address token1; uint256 value1; address token2; uint256 value2; uint8 executed; // 0 - pending, 1 - executed, 2 - cancelled } mapping(uint256 => Swap) swaps; function GETSWAP929(uint256 _id) //inject NONSTANDARD NAMING public view returns (address, address, uint256, address, uint256, uint8) { Swap memory swap = swaps[_id]; return ( swap.aliceAddress, swap.token1, swap.value1, swap.token2, swap.value2, swap.executed ); } function REGISTERSWAP626( //inject NONSTANDARD NAMING uint256 _id, address _aliceAddress, address _token1, uint256 _value1, address _token2, uint256 _value2) public returns (bool) { require(_id != 0); require(_aliceAddress != address(0)); require(_token1 != address(0)); require(_value1 != 0); require(_token2 != address(0)); require(_value2 != 0); Swap storage swap = swaps[_id]; require(swap.aliceAddress == address(0), "Swap already exists"); swap.aliceAddress = _aliceAddress; swap.token1 = _token1; swap.value1 = _value1; swap.token2 = _token2; swap.value2 = _value2; return true; } function CANCELSWAP640(uint256 _id) public returns (bool) { //inject NONSTANDARD NAMING Swap storage swap = swaps[_id]; require(swap.executed == 0, "Swap not available"); swap.executed = 2; } function EXECUTESWAP306(uint256 _id, address _bob) //inject NONSTANDARD NAMING public returns (bool) { require(_bob != address(0)); Swap storage swap = swaps[_id]; require(swap.aliceAddress != address(0), "Swap does not exists"); require(swap.executed == 2, "Swap not available"); IERC20 Token1 = IERC20(swap.token1); IERC20 Token2 = IERC20(swap.token2); // Swap. Make sure to set the allowances in advance Token1.TRANSFERFROM313(swap.aliceAddress, _bob, swap.value1); Token2.TRANSFERFROM313(_bob, swap.aliceAddress, swap.value2); swap.executed = 1; return true; } }
inject NONSTANDARD NAMING
function APPROVE113(address spender, uint256 amount) external returns (bool);
6,449,027
pragma solidity ^0.5.13; import "./interfaces/IRandom.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "../common/CalledByVm.sol"; import "../common/Initializable.sol"; import "../common/UsingPrecompiles.sol"; import "../common/interfaces/ICeloVersionedContract.sol"; /** * @title Provides randomness for verifier selection */ contract Random is IRandom, ICeloVersionedContract, Ownable, Initializable, UsingPrecompiles, CalledByVm { using SafeMath for uint256; /* Stores most recent commitment per address */ mapping(address => bytes32) public commitments; uint256 public randomnessBlockRetentionWindow; mapping(uint256 => bytes32) private history; uint256 private historyFirst; uint256 private historySize; uint256 private lastEpochBlock; event RandomnessBlockRetentionWindowSet(uint256 value); /** * @notice Returns the storage, major, minor, and patch version of the contract. * @return The storage, major, minor, and patch version of the contract. */ function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) { return (1, 1, 1, 0); } /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param _randomnessBlockRetentionWindow Number of old random blocks whose randomness * values can be queried. */ function initialize(uint256 _randomnessBlockRetentionWindow) external initializer { _transferOwnership(msg.sender); setRandomnessBlockRetentionWindow(_randomnessBlockRetentionWindow); } /** * @notice Sets the number of old random blocks whose randomness values can be queried. * @param value Number of old random blocks whose randomness values can be queried. */ function setRandomnessBlockRetentionWindow(uint256 value) public onlyOwner { require(value > 0, "randomnessBlockRetetionWindow cannot be zero"); randomnessBlockRetentionWindow = value; emit RandomnessBlockRetentionWindowSet(value); } /** * @notice Implements step of the randomness protocol. * @param randomness Bytes that will be added to the entropy pool. * @param newCommitment The hash of randomness that will be revealed in the future. * @param proposer Address of the block proposer. * @dev If the Random contract is pointed to by the Registry, the first transaction in a block * should be a special transaction to address 0x0 with 64 bytes of data - the concatenated * `randomness` and `newCommitment`. Before running regular transactions, this function should be * called. */ function revealAndCommit(bytes32 randomness, bytes32 newCommitment, address proposer) external onlyVm { _revealAndCommit(randomness, newCommitment, proposer); } /** * @notice Implements step of the randomness protocol. * @param randomness Bytes that will be added to the entropy pool. * @param newCommitment The hash of randomness that will be revealed in the future. * @param proposer Address of the block proposer. */ function _revealAndCommit(bytes32 randomness, bytes32 newCommitment, address proposer) internal { require(newCommitment != computeCommitment(0), "cannot commit zero randomness"); // ensure revealed randomness matches previous commitment if (commitments[proposer] != 0) { require(randomness != 0, "randomness cannot be zero if there is a previous commitment"); bytes32 expectedCommitment = computeCommitment(randomness); require( expectedCommitment == commitments[proposer], "commitment didn't match the posted randomness" ); } else { require(randomness == 0, "randomness should be zero if there is no previous commitment"); } // add entropy uint256 blockNumber = block.number == 0 ? 0 : block.number.sub(1); addRandomness(block.number, keccak256(abi.encodePacked(history[blockNumber], randomness))); commitments[proposer] = newCommitment; } /** * @notice Add a value to the randomness history. * @param blockNumber Current block number. * @param randomness The new randomness added to history. * @dev The calls to this function should be made so that on the next call, blockNumber will * be the previous one, incremented by one. */ function addRandomness(uint256 blockNumber, bytes32 randomness) internal { history[blockNumber] = randomness; if (blockNumber % getEpochSize() == 0) { if (lastEpochBlock < historyFirst) { delete history[lastEpochBlock]; } lastEpochBlock = blockNumber; } else { if (historySize == 0) { historyFirst = blockNumber; historySize = 1; } else if (historySize > randomnessBlockRetentionWindow) { deleteHistoryIfNotLastEpochBlock(historyFirst); deleteHistoryIfNotLastEpochBlock(historyFirst.add(1)); historyFirst = historyFirst.add(2); historySize = historySize.sub(1); } else if (historySize == randomnessBlockRetentionWindow) { deleteHistoryIfNotLastEpochBlock(historyFirst); historyFirst = historyFirst.add(1); } else { // historySize < randomnessBlockRetentionWindow historySize = historySize.add(1); } } } /** * @notice Compute the commitment hash for a given randomness value. * @param randomness The value for which the commitment hash is computed. * @return Commitment parameter. */ function computeCommitment(bytes32 randomness) public pure returns (bytes32) { return keccak256(abi.encodePacked(randomness)); } /** * @notice Querying the current randomness value. * @return Returns the current randomness value. */ function random() external view returns (bytes32) { return _getBlockRandomness(block.number, block.number); } /** * @notice Get randomness values of previous blocks. * @param blockNumber The number of block whose randomness value we want to know. * @return The associated randomness value. */ function getBlockRandomness(uint256 blockNumber) external view returns (bytes32) { return _getBlockRandomness(blockNumber, block.number); } /** * @notice Get randomness values of previous blocks. * @param blockNumber The number of block whose randomness value we want to know. * @param cur Number of the current block. * @return The associated randomness value. */ function _getBlockRandomness(uint256 blockNumber, uint256 cur) internal view returns (bytes32) { require(blockNumber <= cur, "Cannot query randomness of future blocks"); require( blockNumber == lastEpochBlock || (blockNumber > cur.sub(historySize) && (randomnessBlockRetentionWindow >= cur || blockNumber > cur.sub(randomnessBlockRetentionWindow))), "Cannot query randomness older than the stored history" ); return history[blockNumber]; } function deleteHistoryIfNotLastEpochBlock(uint256 blockNumber) internal { if (blockNumber != lastEpochBlock) { delete history[blockNumber]; } } }
Used in place of the constructor to allow the contract to be upgradable via proxy. _randomnessBlockRetentionWindow Number of old random blocks whose randomness values can be queried./
function initialize(uint256 _randomnessBlockRetentionWindow) external initializer { _transferOwnership(msg.sender); setRandomnessBlockRetentionWindow(_randomnessBlockRetentionWindow); }
14,051,038
./full_match/42/0xC5B258E60C7C87eFc3bEA481a50ed95aacCCEAa8/sources/browser/DFBTCV1Factory.sol
_btcVal: btcVal_,_Receive : true,
function addGuarantorNode(address[] memory _tokenList, uint[] memory _valueList, uint _pledgeCycle, string memory _btcAddress) public payable returns (bool){ require(_tokenList.length>0, "dfbtc: Array length must be greater than 0!!!"); require(_tokenList.length==_valueList.length, "dfbtc: Array length must be equal!!!"); require(cycle[_pledgeCycle], "dfbtc: The period value is not within the set range!"); require(!guarantUserMap[msg.sender]._bExist, "dfbtc: Guarantor already exists!"); uint btcVal_ = addTokenToPools(_tokenList, _valueList, msg.value); User memory _user = User({ _eth : msg.sender, _startTime : now, _pledgeCycle : _pledgeCycle*1 days, _curBTC : 0, _btc : _btcAddress, _bReceive : true, _bExist : true }); guarantorList.push(msg.sender); guarantUserMap[msg.sender] = _user; IERC20(dfbtcAddress).mint(address(this), uint(btcVal_).mul(btcToDfbtc)); return true; }
9,595,366
./full_match/4/0x589d3dC627E3dF4f29BE0f66181925125c0D093C/sources/contracts/Frame.sol
Internal: checks if a token is currently owned by address _tokenId The token to check is owned _address The address to check if it's owned by/
function _tokenIsOwned(uint256 _tokenId, address _address) internal view returns (bool) { return _address == ownerOf(_tokenId); }
668,190
./full_match/1/0xa462127735352B1F03dA8Ab92a87803d05cc6a7B/sources/contracts/Aswang/AswangTribe.sol
@inheritdoc ERC721A Cannot transfer while token is !praying/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public override(IERC721A, ERC721A) { if (tokenInfo[tokenId].prayingStartedAt != 0) revert AswangTribe_TokenPraying(); ERC721A.safeTransferFrom(from, to, tokenId, data); }
8,311,096
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/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/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol) pragma solidity ^0.8.0; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // ROBOTOVERSE NFT CONSTRUCTOR /** * Contract Developed by @itsDigidal * https://twitter.com/itsdigidal * * */ pragma solidity ^0.8.7; contract Robotoverse is ERC721Enumerable, Ownable{ using Strings for uint256; /* base attributes */ string public baseURI; string public prerevealURI; string public baseExtension = ".json"; /* minting prices */ uint256 public batchOnePrice = 0.08 ether; uint256 public batchTwoPrice = 0.1 ether; uint256 public batchThreePrice = 0.15 ether; uint256 public batchFourPrice = 0.2 ether; /* supply */ uint256 public maxSupply; uint256 public maxMintAmount = 100; uint256 public tokenCounter; uint256 public batchOneMembers = 1000; uint256 public batchTwoMembers = 1500; uint256 public batchThreeMembers = 1500; uint256 public batchFourMembers = 3477; uint256 public teamNFTs = 300; uint256 public teamClaimed = 0; /* states */ bool public batchOneActive = true; bool public batchTwoActive = false; bool public batchThreeActive = false; bool public batchFourActive = false; bool public whitelistOpen = false; bool public revealed = false; bool public whitelistActive = true; bool private teamNFTsclaimed = false; /* tax getters */ address private ownerOne; address private ownerTwo; address private ownerThree; uint256 private shareOne = 50; uint256 private shareTwo = 50; uint256 public accountOne = 0 ether; uint256 public accountTwo = 0 ether; /* whitelist params */ uint256 public maxWhitelistAmount = 100; uint256 public whitelistAmount = 1000; uint256 public whitelistSize = 0; mapping(address => bool) public whitelist; event AddedToWhitelist(address indexed account); mapping(address => uint256) whitelistClaimed; // constructor constructor(string memory _newBaseURI, string memory _prerevealURI, address _ownerOne, address _ownerTwo) ERC721("Robotoverse", "RBV") { tokenCounter = 0; maxSupply = batchOneMembers + batchTwoMembers + batchThreeMembers + batchFourMembers; baseURI = _newBaseURI; prerevealURI = _prerevealURI; ownerOne = _ownerOne; ownerTwo = _ownerTwo; } /// public minting function mintNFT(address _to, uint256 _mintAmount) public payable { require(_mintAmount > 0, "At least one token must be minted"); require(_mintAmount <= maxMintAmount, "Exceeds maximal possible tokens to mint on a try"); require(tokenCounter + _mintAmount <= maxSupply, "Maximal supply of NFT is reached"); require(!whitelistActive, "Whitelist Minting is active. Please use other function"); uint256 toPay = 0; if(tokenCounter >= 0 && tokenCounter + _mintAmount <= batchOneMembers) { require(batchOneActive == true, "Batch one can not be minted yet"); require(msg.value >= batchOnePrice * _mintAmount, "Amount of MOVR is to less"); toPay = batchOnePrice * _mintAmount; } else { if(tokenCounter + _mintAmount <= batchOneMembers + batchTwoMembers) { require(batchTwoActive == true, "Batch two can not be minted yet"); require(msg.value >= batchTwoPrice * _mintAmount, "Amount of MOVR is to less"); toPay = batchOnePrice * _mintAmount; } else { if(tokenCounter + _mintAmount <= batchOneMembers + batchTwoMembers + batchThreeMembers) { require(batchThreeActive == true, "Batch two can not be minted yet"); require(msg.value >= batchThreePrice * _mintAmount, "Amount of MOVR is to less"); toPay = batchOnePrice * _mintAmount; } else { require(batchThreeActive == true, "Batch three can not be minted yet"); require(msg.value >= batchThreePrice * _mintAmount, "Amount of MOVR is to less"); toPay = batchOnePrice * _mintAmount; } } } for (uint256 i = 1; i <= _mintAmount; i++) { tokenCounter++; _safeMint(_to, tokenCounter); } /* pay taxes */ accountOne = accountOne + toPay * shareOne / 100; accountTwo = accountTwo + toPay * shareTwo / 100; } // public minting function mintWhitelistNFT(address _to, uint256 _mintAmount) public payable { require(_mintAmount > 0, "At least one token must be minted"); require(_mintAmount <= maxMintAmount, "Exceeds maximal possible tokens to mint on a try"); require(tokenCounter + _mintAmount <= maxSupply, "Maximal supply of NFT is reached"); require(tokenCounter + _mintAmount <= batchOneMembers, "Maximal whitelist NFT's exceeded"); require(isWhitelisted(msg.sender), "You are not whitelisted!"); require(batchOneActive == true, "Batch one can not be minted yet"); require(maxWhitelistAmount >= _mintAmount, "Only five mints are allowed for whitlist users"); require(_mintAmount + getWhitelistClaim(msg.sender) <= maxWhitelistAmount, "You exceeded your whitelist limit"); require(msg.value >= batchOnePrice * _mintAmount, "Amount of ETH is to less"); for (uint256 i = 1; i <= _mintAmount; i++) { tokenCounter++; whitelistClaimed[msg.sender] += 1; _safeMint(_to, tokenCounter); /* pay taxes */ accountOne += msg.value * shareOne / 100; accountTwo += msg.value * shareTwo / 100; } } // read URI of Token for Meta function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI; if (revealed) { currentBaseURI = baseURI; } else { currentBaseURI = prerevealURI; } return string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)); } // get NFT of specific address function getNFTContract(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } // get current amount of NFT function getNFTAmount() public view returns (uint256) { return tokenCounter; } // get current Price for minting depending on batch state function currentMintingPrice() public view returns (uint256) { if(tokenCounter >= 0 && tokenCounter < batchOneMembers) { return batchOnePrice; } else { if(tokenCounter < batchOneMembers + batchTwoMembers) { return batchTwoPrice; } else { if(tokenCounter < batchOneMembers + batchTwoMembers + batchThreeMembers) { return batchThreePrice; } else { return batchFourPrice; } } } } // get baseURI of nft collection function getBaseURI() public view returns (string memory) { return baseURI; } // check is user is whitelisted function isWhitelisted(address _address) public view returns(bool) { return whitelist[_address]; } // check whitelist claims per user function getWhitelistClaim(address _address) public view returns(uint256) { return whitelistClaimed[_address]; } // only owner functions // set price of first batch function setbatchOnePrice(uint256 _newPrice) public onlyOwner { batchOnePrice = _newPrice; } // set price of second batch function setbatchTwoPrice(uint256 _newPrice) public onlyOwner { batchTwoPrice = _newPrice; } // set price of third batch function setbatchThreePrice(uint256 _newPrice) public onlyOwner { batchThreePrice = _newPrice; } // set price of fourth batch function setbatchFourPrice(uint256 _newPrice) public onlyOwner { batchFourPrice = _newPrice; } // set maximal amout of nft to mint on one occasion function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } // change base uri function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } // change prereveal uri function setPrerevealURI(string memory _newBaseURI) public onlyOwner { prerevealURI = _newBaseURI; } // change extension of base uri function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } // activate batchOne function setbatchOneState() public onlyOwner { if(batchOneActive) { batchOneActive = false; } else { batchOneActive = true; } } // activate batchTwo function setbatchTwoState() public onlyOwner { if(batchTwoActive) { batchTwoActive = false; } else { batchTwoActive = true; } } // activate batchThree function setbatchThreeState() public onlyOwner { if(batchThreeActive) { batchThreeActive = false; } else { batchThreeActive = true; } } // activate revealed function setRevealed() public onlyOwner { if(revealed) { revealed = false; } else { revealed = true; } } // withdrawel functions // withdrawel of account function withdrawAccount() public payable { if(msg.sender == ownerOne) { require(accountOne >= 0 ether, "Account One has no credits"); require(payable(msg.sender).send(accountOne)); accountOne = 0; } if(msg.sender == ownerTwo) { require(accountTwo >= 0 ether, "Account Two has no credits"); require(payable(msg.sender).send(accountTwo)); accountTwo = 0; } } // withdrawel of rest function withdraw() public payable onlyOwner { uint256 restAmount = address(this).balance - accountOne - accountTwo; if(restAmount >= 0) { require(payable(msg.sender).send(restAmount)); } } // bulk upload of whitelist users function bulkSetWhitelist(address[] memory accounts) public onlyOwner returns (uint256) { uint256 taskCounter = 0; for (uint256 i = 0; i < accounts.length; i++) { if(!whitelist[accounts[i]]) { if(whitelistSize < whitelistAmount) { whitelist[accounts[i]] = true; emit AddedToWhitelist(accounts[i]); whitelistSize++; taskCounter++; } else { break; } } } return taskCounter; } // activate whitelist minting function setWhitelistOpen() public onlyOwner { if(whitelistActive) { whitelistActive = false; } else { whitelistActive = true; } } // mint teamNFTs function mintTeamNFT(uint256 _toMint) public onlyOwner { require(!teamNFTsclaimed, "TeamNFT already claimed"); teamClaimed += _toMint; if(teamClaimed >= teamNFTs) { teamNFTsclaimed = true; } require(teamClaimed <= teamNFTs, "Maximum of team claims reached"); for (uint256 i = 1; i <= _toMint; i++) { tokenCounter++; _safeMint(msg.sender, tokenCounter); } } }
get baseURI of nft collection
function getBaseURI() public view returns (string memory) { return baseURI; }
6,091,560