file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/3/0xbf400eD5ec1D707B3EfFb6554F18728880Aae52b/sources/YgfStaking.sol
To unstake token user will call this method user will get penalty if they unstack before 84 days user get daily rewards according to calulation sub from totalStackAmount what user stacke erlier so if there is no stacke it wil become zero for first 28 days we give 0.5 rewards per day after 29 day reward is 1% per day
function unStake() external returns (bool) { require(stakedAmount[msg.sender] != 0, "ERR_NOT_STACKED"); uint256 lastStackTime = lastStack[msg.sender]; uint256 amount = stakedAmount[msg.sender]; uint256 _days = safeDiv(safeSub(block.timestamp, lastStackTime), 86400); uint256 totalReward = 0; if (_days > rewardBreakingPoint) { totalReward = safeMul( safeDiv(safeMul(amount, aterBreakPoint), 10000), safeSub(_days, rewardBreakingPoint) ); _days = rewardBreakingPoint; } totalReward = safeAdd( totalReward, safeMul(safeDiv(safeMul(amount, beforeBreakPoint), 10000), _days) ); uint256 totalAmount = safeAdd(amount, totalReward); uint256 penalty = penalityChecker(_days); uint256 penaltyAmount = safeDiv(safeMul(totalAmount, penalty), 10000); uint256 recivedAmount = safeSub(totalAmount, penaltyAmount); emit Unstaked(msg.sender, recivedAmount); IERC20(SurgedToken).transfer(msg.sender, recivedAmount); totalStackAmount = safeSub(totalStackAmount, amount); stakedAmount[msg.sender] = 0; lastStack[msg.sender] = 0; return true; }
5,130,520
contract LockMyEther { //Author: General_Illus //Date: 3/6/2016 //Version: LockMyEther v1.0 address owner; mapping (address => uint) fees; struct User { uint balance; // user balance uint expiration_block; // block ether is unlocked bool trickle; // turn trickle on/off uint trickle_block; // last block user attempted trickle witdrawal } mapping (address => User) user; // Constructor function LockMyEther(){ owner = msg.sender; fees[owner] = 0; } // Default function function() { main(); } // Deposit funds. User cannot alter expiration block once set. Can deposit more Ether though function main() { // Pay half of a percent fee to depost funds uint fee = msg.value / 200; fees[owner] += fee; // Deposit Funds uint deposit = msg.value - fee; user[msg.sender].balance += deposit; if (user[msg.sender].expiration_block > 0) return; user[msg.sender].expiration_block = 0; } // Withdraw funds function withdraw() { // Trickle is on, so allow withdraw based on variance between expiration block and last withdraw block if (user[msg.sender].trickle == true && user[msg.sender].expiration_block > block.number) { uint balance_per_block = user[msg.sender].balance / (user[msg.sender].expiration_block - user[msg.sender].trickle_block); uint trickle_balance = balance_per_block * (block.number - user[msg.sender].trickle_block); msg.sender.send(trickle_balance); user[msg.sender].balance = user[msg.sender].balance - trickle_balance; user[msg.sender].trickle_block = block.number; } // Trickle is off, test is current block is greater than expiration block, if true then withdraw else { if (user[msg.sender].expiration_block > block.number) return; msg.sender.send(user[msg.sender].balance); user[msg.sender].balance = 0; user[msg.sender].expiration_block = 0; } } // Withdraw fees function withdrawFees() { if (msg.sender == owner) owner.send(fees[owner]); fees[owner] = 0; } // Check balance of account function getBalance() constant returns (uint Balance) { return user[msg.sender].balance; } // Check balance of fee account function getFeeBalance() constant returns (uint FeeBalance) { if (msg.sender == owner) return fees[owner]; } // Get latest block number function getLatestBlock() constant returns (uint BlockNumber) { return block.number; } // Get expiration block function getExpirationBlock() constant returns (uint ExpirationBlock) { return user[msg.sender].expiration_block; } // Get trickle block function getTrickleBlock() constant returns (uint TrickleBlock) { return user[msg.sender].trickle_block; } // Get trickle status function getTrickle() constant returns (bool Trickle) { return user[msg.sender].trickle; } // Set expiration block function setExpirationBlock(uint _blocknumber) { // Do not allow anyone to set an expiration after one has already been set if (user[msg.sender].expiration_block > 0) return; // Do not allow anyone to set an expiration that is more than 9M blocks into future if (_blocknumber > block.number+9000000) return; user[msg.sender].expiration_block = _blocknumber; } //Turn trickle on function setTrickleOn() { user[msg.sender].trickle = true; user[msg.sender].trickle_block = block.number; } //Turn trickle off function setTrickleOff() { user[msg.sender].trickle = false; } // Suicide the contract //function destroyContract() { // if (msg.sender == owner){ // suicide(owner); // } //} }
Get expiration block
function getExpirationBlock() constant returns (uint ExpirationBlock) { return user[msg.sender].expiration_block; }
6,456,031
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT import "../../core/DaoConstants.sol"; import "../../core/DaoRegistry.sol"; import "../../guards/AdapterGuard.sol"; import "../IExtension.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** MIT License Copyright (c) 2020 Openlaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract NFTExtension is DaoConstants, AdapterGuard, IExtension, IERC721Receiver { using Address for address payable; // Add the library methods using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; bool public initialized = false; // internally tracks deployment under eip-1167 proxy pattern DaoRegistry public dao; address private _creator; enum AclFlag {TRANSFER_NFT, RETURN_NFT, REGISTER_NFT} // All the NFTs and Token ids that belong to the GUILD mapping(address => mapping(address => EnumerableSet.UintSet)) private _nftCollection; // All the NFTs addresses collected and stored in the GUILD collection EnumerableSet.AddressSet private _collectedNFTs; // The NFTs addresses supported by the extension mapping(address => bool) public availableNFTs; modifier hasExtensionAccess(IExtension extension, AclFlag flag) { require( dao.state() == DaoRegistry.DaoState.CREATION || dao.hasAdapterAccessToExtension( msg.sender, address(extension), uint8(flag) ), "nft::accessDenied" ); _; } modifier isCreatorOrHasExtensionAccess(IExtension extension, AclFlag flag) { require( msg.sender == _creator || dao.state() == DaoRegistry.DaoState.CREATION || dao.hasAdapterAccessToExtension( msg.sender, address(extension), uint8(flag) ), "nft::accessDenied::notCreator" ); _; } /// @notice Clonable contract must have an empty constructor constructor() {} /** * @notice Initializes the extension with the DAO address that it belongs too. * @param _dao The address of the DAO that owns the extension. * @param creator The owner of the DAO and Extension that is also a member of the DAO. */ function initialize(DaoRegistry _dao, address creator) external override { require(!initialized, "already initialized"); require(_dao.isActiveMember(creator), "not active member"); initialized = true; _creator = creator; dao = _dao; } /** * @notice Collects the NFT from the owner and moves to the contract address * @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param owner The owner of the NFT that wants to store it in the DAO. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function collect( address owner, address nftAddr, uint256 nftTokenId ) external { require(isNFTAllowed(nftAddr), "nft not allowed"); IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address erc721.safeTransferFrom(owner, address(this), nftTokenId); // Save the asset in the GUILD collection _nftCollection[GUILD][nftAddr].add(nftTokenId); // Keep track of the collected assets _collectedNFTs.add(nftAddr); } /** * @notice Internally transfer the NFT token from the escrow adapter to the extension address. * @notice It also updates the internal state to keep track of the all the NFTs collected by the extension. * @notice It must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * @notice The caller must have the ACL Flag: TRANSFER_NFT * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param escrowAddr The address of the escrow adapter, usually it is the address of the TributeNFT adapter. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function transferFrom( address escrowAddr, address nftAddr, uint256 nftTokenId ) public hasExtensionAccess(this, AclFlag.TRANSFER_NFT) { require(isNFTAllowed(nftAddr), "non allowed nft"); IERC721 erc721 = IERC721(nftAddr); // Move the NFT to the contract address erc721.safeTransferFrom(escrowAddr, address(this), nftTokenId); // Save the asset in the GUILD collection _nftCollection[GUILD][nftAddr].add(nftTokenId); // Keep track of the collected assets _collectedNFTs.add(nftAddr); } /** * @notice Ttransfers the NFT token from the extension address to the new owner. * @notice It also updates the internal state to keep track of the all the NFTs collected by the extension. * @notice The caller must have the ACL Flag: RETURN_NFT * @dev Reverts if the NFT is not support/allowed, or is not in ERC721 standard. * @param newOwner The address of the new owner. * @param nftAddr The NFT address that must be in ERC721 and allowed/supported by the extension. * @param nftTokenId The NFT token id. */ function returnNFT( address newOwner, address nftAddr, uint256 nftTokenId ) public hasExtensionAccess(this, AclFlag.RETURN_NFT) { require(isNFTAllowed(nftAddr), "nft not allowed"); // Remove the NFT from the contract address to the actual owner IERC721 erc721 = IERC721(nftAddr); erc721.safeTransferFrom(address(this), newOwner, nftTokenId); // Remove the asset from the GUILD collection _nftCollection[GUILD][nftAddr].remove(nftTokenId); // If we dont hold the asset anymore, we can remove it if (_nftCollection[GUILD][nftAddr].length() == 0) { _collectedNFTs.remove(nftAddr); } } /** * @notice Registers a potential new NFT in the NFT extension. * @notice The caller must have the ACL Flag: REGISTER_NFT. * @dev Reverts if the token address is reserved. * @param nftAddr The address of the new NFT. */ function registerPotentialNewNFT(address nftAddr) public isCreatorOrHasExtensionAccess(this, AclFlag.REGISTER_NFT) { require( isNotReservedAddress(nftAddr) && nftAddr != SHARES, "reservedToken" ); if (!availableNFTs[nftAddr]) { availableNFTs[nftAddr] = true; } } /** * @notice Checks if a given token address is allowed/supported by the extension. */ function isNFTAllowed(address nftAddr) public view returns (bool) { return availableNFTs[nftAddr]; } /** * @notice Returns the total amount of NFTs collected. */ function nbNFTs() public view returns (uint256) { return _collectedNFTs.length(); } /** * @notice Returns NFT address stored in the GUILD collection at the specified index. * @param index The index to get the NFT address if it exists */ function getNFTByIndex(uint256 index) public view returns (address) { return _collectedNFTs.at(index); } /** * @notice Required function from IERC721 standard to be able to receive assets to this contract address */ function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return this.onERC721Received.selector; } }
Registers a potential new NFT in the NFT extension. The caller must have the ACL Flag: REGISTER_NFT. Reverts if the token address is reserved. nftAddr The address of the new NFT./
function registerPotentialNewNFT(address nftAddr) public isCreatorOrHasExtensionAccess(this, AclFlag.REGISTER_NFT) { require( isNotReservedAddress(nftAddr) && nftAddr != SHARES, "reservedToken" ); if (!availableNFTs[nftAddr]) { availableNFTs[nftAddr] = true; } }
12,768,460
./full_match/1/0x7fFd853A30A0Bf3f97F06301890B245f212a2de4/sources/contracts/MEDIFAKT.sol
Decreases the allowance of `spender` by `amount`./
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "FAKT: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; }
16,438,636
pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title GoSwap 质押合约 */ contract GoSwapStake is ERC20("GoSwap Stake", "sGOT"){ using SafeMath for uint256; IERC20 public GOT; /** * @dev 构造函数 * @param _GOT GoSwap Token地址 */ constructor(IERC20 _GOT) public { GOT = _GOT;// 0x6b3595068778dd592e39a122f4f5a5cf09c90fe2 } /** * @dev 进入吧台,将自己的GoSwap Token发送到合约换取份额 * @param _amount GoSwap Token数额 */ // 进入吧台, 支付一些GOT, 赚取份额 // Enter the bar. Pay some GOT. Earn some shares. function enter(uint256 _amount) public { // 当前合约的GoSwap Token余额 uint256 totalGOT = GOT.balanceOf(address(this)); // 当前合约的总发行量 uint256 totalShares = totalSupply(); // 如果 当前合约的总发行量 == 0 || 当前合约的总发行量 == 0 if (totalShares == 0 || totalGOT == 0) { // 当前合约铸造amount数量的token给调用者 _mint(msg.sender, _amount); } else { // what数额 = 数额 * 当前合约的总发行量 / 当前合约的GoSwap Token余额 uint256 what = _amount.mul(totalShares).div(totalGOT); // 当前合约铸造what数量的token给调用者 _mint(msg.sender, what); } // 将amount数量的GoSwap Token从调用者发送到当前合约地址 GOT.transferFrom(msg.sender, address(this), _amount); } /** * @dev 离开吧台,取回自己的GoSwap Token * @param _share GOT数额 */ // Leave the bar. Claim back your GOT. function leave(uint256 _share) public { // 当前合约的总发行量 uint256 totalShares = totalSupply(); // what数额 = 份额 * 当前合约在GoSwap Token的余额 / 当前合约的总发行量 uint256 what = _share.mul(GOT.balanceOf(address(this))).div(totalShares); // 为调用者销毁份额 _burn(msg.sender, _share); // 将what数额的GoSwap Token发送到调用者账户 GOT.transfer(msg.sender, what); } }
离开吧台,取回自己的GoSwap Token _share GOT数额/ Leave the bar. Claim back your GOT. 当前合约的总发行量 what数额 = 份额 当前合约在GoSwap Token的余额 / 当前合约的总发行量 为调用者销毁份额 将what数额的GoSwap Token发送到调用者账户
function leave(uint256 _share) public { uint256 totalShares = totalSupply(); uint256 what = _share.mul(GOT.balanceOf(address(this))).div(totalShares); _burn(msg.sender, _share); GOT.transfer(msg.sender, what); }
7,273,240
pragma solidity >=0.4.0 <0.6.0; import "./Book.sol"; import "./Publisher.sol"; contract Author { string public name; address[] public publishedBooks; address[] public unpublishedBooks; address myAddress; struct Request { address publisher; string ipfsHash; address bookAddr; } Request[] requests; //modifiers modifier OnlyMe() { require(msg.sender == myAddress, 'You are not the author :('); _; } modifier NotMe() { require(msg.sender != myAddress, 'You are the author :('); _; } constructor(string memory _name) public { name = _name; myAddress = msg.sender; } function getAuthor() view public returns(address) { return ( myAddress ) ; } function addNewBook(string memory title, string memory ipfsHash) OnlyMe public { //TODO: check if the book exists address book = address(new Book(title, ipfsHash, address(this))); unpublishedBooks.push(book); } function getLatestBookAddress() view OnlyMe public returns (address) { return (unpublishedBooks[unpublishedBooks.length -1 ] ) ; } function requestApproval(address _pubAddr, string memory _ipfsHash, address _bookAddr) NotMe public { requests.push(Request(_pubAddr, _ipfsHash, _bookAddr)); //add event } function getRequestIndex() view public returns( uint ) { return (requests.length); } function approveRequest(uint index) public { Book book = Book(requests[index].bookAddr); //Publisher publisher = Publisher(requests[index].publisher); //TODO: check book exists, doest not have a publisher, publisher exists // require(book.publisher == 0); if(keccak256(abi.encodePacked(requests[index].ipfsHash)) == keccak256(abi.encodePacked(book.ipfsHash))) { book.setPublisher(requests[index].publisher); //publisher.requestApproved(requests[index].bookAddr); publishedBooks.push(requests[index].bookAddr); uint i; for(i = 0;i < unpublishedBooks.length;i++) { if(unpublishedBooks[i] == requests[index].bookAddr) { break; } } delete unpublishedBooks[i]; //inform publisher //add to publisher list } } }
Publisher publisher = Publisher(requests[index].publisher);TODO: check book exists, doest not have a publisher, publisher exists require(book.publisher == 0);publisher.requestApproved(requests[index].bookAddr);
function approveRequest(uint index) public { Book book = Book(requests[index].bookAddr); if(keccak256(abi.encodePacked(requests[index].ipfsHash)) == keccak256(abi.encodePacked(book.ipfsHash))) { book.setPublisher(requests[index].publisher); publishedBooks.push(requests[index].bookAddr); uint i; for(i = 0;i < unpublishedBooks.length;i++) { if(unpublishedBooks[i] == requests[index].bookAddr) { break; } } delete unpublishedBooks[i]; }
5,361,102
pragma solidity ^0.4.23; /** * Math operations with safety checks */ library SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * c + a % b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function safePerc(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= 0); uint256 c = (a * b) / 100; return c; } /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract CSC { event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; mapping (address => uint256) private balances; mapping (address => uint256[2]) private lockedBalances; mapping (address => mapping (address => uint256)) internal allowed; /* External Functions */ constructor( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, address _owner, address[] _lockedAddress, uint256[] _lockedBalances, uint256[] _lockedTimes ) public { balances[_owner] = _initialAmount; // Give the owner all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes owner = _owner; // set owner for(uint i = 0;i < _lockedAddress.length;i++){ lockedBalances[_lockedAddress[i]][0] = _lockedBalances[i]; lockedBalances[_lockedAddress[i]][1] = _lockedTimes[i]; } } /* External Functions */ /*DirectDrop and AirDrop*/ /*With permission, destory token from an address and minus total amount.*/ function burnFrom(address _who,uint256 _value)public returns (bool){ require(msg.sender == owner); assert(balances[_who] >= _value); totalSupply -= _value; balances[_who] -= _value; lockedBalances[_who][0] = 0; lockedBalances[_who][1] = 0; return true; } /*With permission, creating coin.*/ function makeCoin(uint256 _value)public returns (bool){ require(msg.sender == owner); totalSupply += _value; balances[owner] += _value; return true; } /*With permission, withdraw ETH to owner address from smart contract.*/ function withdraw() public{ require(msg.sender == owner); msg.sender.transfer(address(this).balance); } /*With permission, withdraw ETH to an address from smart contract.*/ function withdrawTo(address _to) public{ require(msg.sender == owner); address(_to).transfer(address(this).balance); } function checkValue(address _from,uint256 _value) private view{ if(lockedBalances[_from][1] >= now) { require(balances[_from].sub(lockedBalances[_from][0]) >= _value); } else { require(balances[_from] >= _value); } } /** * @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)); checkValue(msg.sender,_value); 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) { //Before ICO finish, only own could transfer. require(_to != address(0)); checkValue(_from,_value); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } }
Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/Before ICO finish, only own could transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); checkValue(_from,_value); 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; }
1,067,741
// 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); } }
Version of the governor instance (used in building the ERC712 domain separator). Default: "1"/
function governorVersion() public pure returns (string memory) { return "1"; }
1,795,157
./full_match/1/0xDC14f5dba4eA0175ce8C5351396CE8406d21fb4b/sources/contracts/Auction.sol
Gets the current data of the auction. return data A struct containing the highest bidder and the highest bid amount of the auction.
function getData() external view returns (AuctionData memory) { return auctionData; }
2,933,179
/** *Submitted for verification at Etherscan.io on 2021-06-27 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Pausable is Ownable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } 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 Pausable, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address, address, uint256) internal virtual { require(!paused(), "ERC20Pausable: token transfer while paused"); } } /* _______ |_ _|.-----.---.-. .-----.--.--. _| |_ |__ --| _ | | | | | |_______||_____|___._| |__|__|___ | |_____| __ .---.-.--------.-----.-----.| |_.---.-.-----.---.-. | _ | | _ | || _| _ | | _ | |___._|__|__|__|_____|__|__||____|___._|__|__|___._| */ contract Dralako is ERC20 { bool public mintStopped = false; constructor() ERC20("Dralako - Isa ny Amontana", "DRALA") { } function mint(address account, uint256 amount) public onlyOwner returns (bool) { require(!mintStopped, "mint is stopped"); _mint(account, amount); return true; } function stopMint() public onlyOwner { mintStopped = true; } }
See {ERC20-_beforeTokenTransfer}. Requirements: - the contract must not be paused./
function _beforeTokenTransfer(address, address, uint256) internal virtual { require(!paused(), "ERC20Pausable: token transfer while paused"); }
6,643,251
/** *Submitted for verification at Etherscan.io on 2021-09-17 */ // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/root/RootChainManager/IRootChainManager.sol pragma solidity 0.6.6; interface IRootChainManager { event TokenMapped( address indexed rootToken, address indexed childToken, bytes32 indexed tokenType ); event PredicateRegistered( bytes32 indexed tokenType, address indexed predicateAddress ); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function cleanMapToken( address rootToken, address childToken ) external; function remapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } // File: contracts/root/StateSender/IStateSender.sol pragma solidity 0.6.6; interface IStateSender { function syncState(address receiver, bytes calldata data) external; } // File: contracts/root/ICheckpointManager.sol pragma solidity 0.6.6; contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } // File: contracts/root/RootChainManager/RootChainManagerStorage.sol pragma solidity 0.6.6; abstract contract RootChainManagerStorage { mapping(bytes32 => address) public typeToPredicate; mapping(address => address) public rootToChildToken; mapping(address => address) public childToRootToken; mapping(address => bytes32) public tokenToType; mapping(bytes32 => bool) public processedExits; IStateSender internal _stateSender; ICheckpointManager internal _checkpointManager; address public childChainManagerAddress; } // File: contracts/lib/RLPReader.sol /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns * https://github.com/hamdiallam/Solidity-RLP/blob/e681e25a376dbd5426b509380bc03446f05d0f97/contracts/RLPReader.sol */ pragma solidity 0.6.6; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param the RLP item. */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param the RLP item. * @return (memPtr, len) pair: location of the item's payload in memory. */ function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) { uint offset = _payloadOffset(item.memPtr); uint memPtr = item.memPtr + offset; uint len = item.len - offset; // data length return (memPtr, len); } /* * @param the RLP item. */ function payloadLen(RLPItem memory item) internal pure returns (uint) { (, uint len) = payloadLocation(item); return len; } /* * @param the RLP item containing the encoded list. */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte except "0x80" is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } // SEE Github Issue #5. // Summary: Most commonly used RLP libraries (i.e Geth) will encode // "0" as "0x80" instead of as "0". We handle this edge case explicitly // here. if (result == 0 || result == STRING_SHORT_START) { return false; } else { return true; } } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); (uint memPtr, uint len) = payloadLocation(item); uint result; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); (uint memPtr, uint len) = payloadLocation(item); bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(memPtr, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len > 0) { // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } } // File: contracts/lib/MerklePatriciaProof.sol /* * @title MerklePatriciaVerifier * @author Sam Mayo ([email protected]) * * @dev Library for verifing merkle patricia proofs. */ pragma solidity 0.6.6; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } // File: contracts/lib/Merkle.sol pragma solidity 0.6.6; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } // File: contracts/root/TokenPredicates/ITokenPredicate.sol pragma solidity 0.6.6; /// @title Token predicate interface for all pos portal predicates /// @notice Abstract interface that defines methods for custom predicates interface ITokenPredicate { /** * @notice Deposit tokens into pos portal * @dev When `depositor` deposits tokens into pos portal, tokens get locked into predicate contract. * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on side chain * @param rootToken Token which gets deposited * @param depositData Extra data for deposit (amount for ERC20, token id for ERC721 etc.) [ABI encoded] */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external; /** * @notice Validates and processes exit while withdraw process * @dev Validates exit log emitted on sidechain. Reverts if validation fails. * @dev Processes withdraw based on custom logic. Example: transfer ERC20/ERC721, mint ERC721 if mintable withdraw * @param sender Address * @param rootToken Token which gets withdrawn * @param logRLPList Valid sidechain log for data like amount, token id etc. */ function exitTokens( address sender, address rootToken, bytes calldata logRLPList ) external; } // File: contracts/common/Initializable.sol pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/EIP712Base.sol pragma solidity 0.6.6; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity 0.6.6; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/common/AccessControlMixin.sol pragma solidity 0.6.6; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } // File: contracts/common/ContextMixin.sol pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File: contracts/root/RootChainManager/RootChainManager.sol pragma solidity 0.6.6; contract RootChainManager is IRootChainManager, Initializable, AccessControl, // included to match old storage layout while upgrading RootChainManagerStorage, // created to match old storage layout while upgrading AccessControlMixin, NativeMetaTransaction, ContextMixin { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; // maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4 bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE"); function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } /** * @notice Deposit ether by directly sending to the contract * The account sending ether receives WETH on child chain */ receive() external payable { _depositEtherFor(_msgSender()); } /** * @notice Initialize the contract after it has been proxified * @dev meant to be called once immediately after deployment * @param _owner the account that should be granted admin role */ function initialize( address _owner ) external initializer { _initializeEIP712("RootChainManager"); _setupContractId("RootChainManager"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MAPPER_ROLE, _owner); } // adding seperate function setupContractId since initialize is already called with old implementation function setupContractId() external only(DEFAULT_ADMIN_ROLE) { _setupContractId("RootChainManager"); } // adding seperate function initializeEIP712 since initialize is already called with old implementation function initializeEIP712() external only(DEFAULT_ADMIN_ROLE) { _setDomainSeperator("RootChainManager"); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external only(DEFAULT_ADMIN_ROLE) { require(newStateSender != address(0), "RootChainManager: BAD_NEW_STATE_SENDER"); _stateSender = IStateSender(newStateSender); } /** * @notice Get the address of contract set as state sender * @return The address of state sender contract */ function stateSenderAddress() external view returns (address) { return address(_stateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external only(DEFAULT_ADMIN_ROLE) { require(newCheckpointManager != address(0), "RootChainManager: BAD_NEW_CHECKPOINT_MANAGER"); _checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Get the address of contract set as checkpoint manager * @return The address of checkpoint manager contract */ function checkpointManagerAddress() external view returns (address) { return address(_checkpointManager); } /** * @notice Set the child chain manager, callable only by admins * @dev This should be the contract responsible to receive deposit bytes on child chain * @param newChildChainManager address of child chain manager contract */ function setChildChainManagerAddress(address newChildChainManager) external only(DEFAULT_ADMIN_ROLE) { require(newChildChainManager != address(0x0), "RootChainManager: INVALID_CHILD_CHAIN_ADDRESS"); childChainManagerAddress = newChildChainManager; } /** * @notice Register a token predicate address against its type, callable only by ADMIN * @dev A predicate is a contract responsible to process the token specific logic while locking or exiting tokens * @param tokenType bytes32 unique identifier for the token type * @param predicateAddress address of token predicate address */ function registerPredicate(bytes32 tokenType, address predicateAddress) external override only(DEFAULT_ADMIN_ROLE) { typeToPredicate[tokenType] = predicateAddress; emit PredicateRegistered(tokenType, predicateAddress); } /** * @notice Map a token to enable its movement via the PoS Portal, callable only by mappers * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function mapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(MAPPER_ROLE) { // explicit check if token is already mapped to avoid accidental remaps require( rootToChildToken[rootToken] == address(0) && childToRootToken[childToken] == address(0), "RootChainManager: ALREADY_MAPPED" ); _mapToken(rootToken, childToken, tokenType); } /** * @notice Clean polluted token mapping * @param rootToken address of token on root chain. Since rename token was introduced later stage, * clean method is used to clean pollulated mapping */ function cleanMapToken( address rootToken, address childToken ) external override only(DEFAULT_ADMIN_ROLE) { rootToChildToken[rootToken] = address(0); childToRootToken[childToken] = address(0); tokenToType[rootToken] = bytes32(0); emit TokenMapped(rootToken, childToken, tokenToType[rootToken]); } /** * @notice Remap a token that has already been mapped, properly cleans up old mapping * Callable only by ADMIN * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function remapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(DEFAULT_ADMIN_ROLE) { // cleanup old mapping address oldChildToken = rootToChildToken[rootToken]; address oldRootToken = childToRootToken[childToken]; if (rootToChildToken[oldRootToken] != address(0)) { rootToChildToken[oldRootToken] = address(0); tokenToType[oldRootToken] = bytes32(0); } if (childToRootToken[oldChildToken] != address(0)) { childToRootToken[oldChildToken] = address(0); } _mapToken(rootToken, childToken, tokenType); } function _mapToken( address rootToken, address childToken, bytes32 tokenType ) private { require( typeToPredicate[tokenType] != address(0x0), "RootChainManager: TOKEN_TYPE_NOT_SUPPORTED" ); rootToChildToken[rootToken] = childToken; childToRootToken[childToken] = rootToken; tokenToType[rootToken] = tokenType; emit TokenMapped(rootToken, childToken, tokenType); bytes memory syncData = abi.encode(rootToken, childToken, tokenType); _stateSender.syncState( childChainManagerAddress, abi.encode(MAP_TOKEN, syncData) ); } /** * @notice Move ether from root to child chain, accepts ether transfer * Keep in mind this ether cannot be used to pay gas on child chain * Use Matic tokens deposited using plasma mechanism for that * @param user address of account that should receive WETH on child chain */ function depositEtherFor(address user) external override payable { _depositEtherFor(user); } /** * @notice Move tokens from root to child chain * @dev This mechanism supports arbitrary tokens as long as its predicate has been registered and the token is mapped * @param user address of account that should receive this deposit on child chain * @param rootToken address of token that is being deposited * @param depositData bytes data that is sent to predicate and child token contracts to handle deposit */ function depositFor( address user, address rootToken, bytes calldata depositData ) external override { require( rootToken != ETHER_ADDRESS, "RootChainManager: INVALID_ROOT_TOKEN" ); _depositFor(user, rootToken, depositData); } function _depositEtherFor(address user) private { bytes memory depositData = abi.encode(msg.value); _depositFor(user, ETHER_ADDRESS, depositData); // payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); // transfer doesn't work as expected when receiving contract is proxified so using call (bool success, /* bytes memory data */) = typeToPredicate[tokenToType[ETHER_ADDRESS]].call{value: msg.value}(""); if (!success) { revert("RootChainManager: ETHER_TRANSFER_FAILED"); } } function _depositFor( address user, address rootToken, bytes memory depositData ) private { bytes32 tokenType = tokenToType[rootToken]; require( rootToChildToken[rootToken] != address(0x0) && tokenType != 0, "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[tokenType]; require( predicateAddress != address(0), "RootChainManager: INVALID_TOKEN_TYPE" ); require( user != address(0), "RootChainManager: INVALID_USER" ); ITokenPredicate(predicateAddress).lockTokens( _msgSender(), user, rootToken, depositData ); bytes memory syncData = abi.encode(user, rootToken, depositData); _stateSender.syncState( childChainManagerAddress, abi.encode(DEPOSIT, syncData) ); } /** * @notice exit tokens by providing proof * @dev This function verifies if the transaction actually happened on child chain * the transaction log is then sent to token predicate to handle it accordingly * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function exit(bytes calldata inputData) external override { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); require(inputDataRLPList.length == 10, "RootChainManager: BAD_PAYLOAD"); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "RootChainManager: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; address childToken = RLPReader.toAddress(logRLP.toList()[0]); // log emitter address field // log should be emmited only by the child token address rootToken = childToRootToken[childToken]; require( rootToken != address(0), "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[ tokenToType[rootToken] ]; // branch mask can be maximum 32 bits require( inputDataRLPList[8].toUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootChainManager: INVALID_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); ITokenPredicate(predicateAddress).exitTokens( _msgSender(), rootToken, logRLP.toRlpBytes() ); } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = _checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootChainManager: INVALID_HEADER" ); return createdAt; } }
payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); transfer doesn't work as expected when receiving contract is proxified so using call
function _depositEtherFor(address user) private { bytes memory depositData = abi.encode(msg.value); _depositFor(user, ETHER_ADDRESS, depositData); if (!success) { revert("RootChainManager: ETHER_TRANSFER_FAILED"); } }
2,282,836
./full_match/1/0x3a32BecC41115b4Aa8bD8614301AeBB9bB11258b/sources/@lyrafinance/protocol/contracts/synthetix/SignedDecimalMath.sol
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. 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 2256. The result is rounded to the nearest increment./
function _divideDecimalRound( int x, int y, int precisionUnit ) private pure returns (int) { int resultTimesTen = (x * (precisionUnit * 10)) / y; return _roundDividingByTen(resultTimesTen); }
9,671,999
// SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import './BaseCDPManager.sol'; import '../interfaces/IOracleRegistry.sol'; import '../interfaces/IOracleUsd.sol'; import '../interfaces/IWETH.sol'; import '../interfaces/IVault.sol'; import '../interfaces/ICDPRegistry.sol'; import '../interfaces/vault-managers/parameters/IVaultManagerParameters.sol'; import '../interfaces/IVaultParameters.sol'; import '../interfaces/IToken.sol'; import '../helpers/ReentrancyGuard.sol'; import '../helpers/SafeMath.sol'; /** * @title CDPManager01 **/ contract CDPManager01 is BaseCDPManager { using SafeMath for uint; address payable public immutable WETH; /** * @param _vaultManagerParameters The address of the contract with Vault manager parameters * @param _oracleRegistry The address of the oracle registry * @param _cdpRegistry The address of the CDP registry * @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters **/ constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) BaseCDPManager(_vaultManagerParameters, _oracleRegistry, _cdpRegistry, _vaultManagerBorrowFeeParameters) { WETH = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault()).weth(); } // only accept ETH via fallback from the WETH contract receive() external payable { require(msg.sender == WETH, "Unit Protocol: RESTRICTED"); } /** * @notice Depositing tokens must be pre-approved to Vault address * @notice Borrow fee in USDP tokens must be pre-approved to CDP manager address * @notice position actually considered as spawned only when debt > 0 * @dev Deposits collateral and/or borrows USDP * @param asset The address of the collateral * @param assetAmount The amount of the collateral to deposit * @param usdpAmount The amount of USDP token to borrow **/ function join(address asset, uint assetAmount, uint usdpAmount) public nonReentrant checkpoint(asset, msg.sender) { require(usdpAmount != 0 || assetAmount != 0, "Unit Protocol: USELESS_TX"); require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS"); if (usdpAmount == 0) { vault.depositMain(asset, msg.sender, assetAmount); } else { _ensureOracle(asset); bool spawned = vault.debts(asset, msg.sender) != 0; if (!spawned) { // spawn a position vault.spawn(asset, msg.sender, oracleRegistry.oracleTypeByAsset(asset)); } if (assetAmount != 0) { vault.depositMain(asset, msg.sender, assetAmount); } // mint USDP to owner vault.borrow(asset, msg.sender, usdpAmount); _chargeBorrowFee(asset, msg.sender, usdpAmount); // check collateralization _ensurePositionCollateralization(asset, msg.sender); } // fire an event emit Join(asset, msg.sender, assetAmount, usdpAmount); } /** * @dev Deposits ETH and/or borrows USDP * @param usdpAmount The amount of USDP token to borrow **/ function join_Eth(uint usdpAmount) external payable { if (msg.value != 0) { IWETH(WETH).deposit{value: msg.value}(); require(IWETH(WETH).transfer(msg.sender, msg.value), "Unit Protocol: WETH_TRANSFER_FAILED"); } join(WETH, msg.value, usdpAmount); } /** * @notice Tx sender must have a sufficient USDP balance to pay the debt * @dev Withdraws collateral and repays specified amount of debt * @param asset The address of the collateral * @param assetAmount The amount of the collateral to withdraw * @param usdpAmount The amount of USDP to repay **/ function exit(address asset, uint assetAmount, uint usdpAmount) public nonReentrant checkpoint(asset, msg.sender) returns (uint) { // check usefulness of tx require(assetAmount != 0 || usdpAmount != 0, "Unit Protocol: USELESS_TX"); uint debt = vault.debts(asset, msg.sender); // catch full repayment if (usdpAmount > debt) { usdpAmount = debt; } if (assetAmount == 0) { _repay(asset, msg.sender, usdpAmount); } else { if (debt == usdpAmount) { vault.withdrawMain(asset, msg.sender, assetAmount); if (usdpAmount != 0) { _repay(asset, msg.sender, usdpAmount); } } else { _ensureOracle(asset); // withdraw collateral to the owner address vault.withdrawMain(asset, msg.sender, assetAmount); if (usdpAmount != 0) { _repay(asset, msg.sender, usdpAmount); } vault.update(asset, msg.sender); _ensurePositionCollateralization(asset, msg.sender); } } // fire an event emit Exit(asset, msg.sender, assetAmount, usdpAmount); return usdpAmount; } /** * @notice Repayment is the sum of the principal and interest * @dev Withdraws collateral and repays specified amount of debt * @param asset The address of the collateral * @param assetAmount The amount of the collateral to withdraw * @param repayment The target repayment amount **/ function exit_targetRepayment(address asset, uint assetAmount, uint repayment) external returns (uint) { uint usdpAmount = _calcPrincipal(asset, msg.sender, repayment); return exit(asset, assetAmount, usdpAmount); } /** * @notice Withdraws WETH and converts to ETH * @param ethAmount ETH amount to withdraw * @param usdpAmount The amount of USDP token to repay **/ function exit_Eth(uint ethAmount, uint usdpAmount) public returns (uint) { usdpAmount = exit(WETH, ethAmount, usdpAmount); require(IWETH(WETH).transferFrom(msg.sender, address(this), ethAmount), "Unit Protocol: WETH_TRANSFER_FROM_FAILED"); IWETH(WETH).withdraw(ethAmount); (bool success, ) = msg.sender.call{value:ethAmount}(""); require(success, "Unit Protocol: ETH_TRANSFER_FAILED"); return usdpAmount; } /** * @notice Repayment is the sum of the principal and interest * @notice Withdraws WETH and converts to ETH * @param ethAmount ETH amount to withdraw * @param repayment The target repayment amount **/ function exit_Eth_targetRepayment(uint ethAmount, uint repayment) external returns (uint) { uint usdpAmount = _calcPrincipal(WETH, msg.sender, repayment); return exit_Eth(ethAmount, usdpAmount); } function _ensurePositionCollateralization(address asset, address owner) internal view { // collateral value of the position in USD uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); // USD limit of the position uint usdLimit = usdValue_q112 * vaultManagerParameters.initialCollateralRatio(asset) / Q112 / 100; // revert if collateralization is not enough require(vault.getTotalDebt(asset, owner) <= usdLimit, "Unit Protocol: UNDERCOLLATERALIZED"); } // Liquidation Trigger /** * @dev Triggers liquidation of a position * @param asset The address of the collateral token of a position * @param owner The owner of the position **/ function triggerLiquidation(address asset, address owner) external nonReentrant { _ensureOracle(asset); // USD value of the collateral uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); // reverts if a position is not liquidatable require(_isLiquidatablePosition(asset, owner, usdValue_q112), "Unit Protocol: SAFE_POSITION"); uint liquidationDiscount_q112 = usdValue_q112.mul( vaultManagerParameters.liquidationDiscount(asset) ).div(DENOMINATOR_1E5); uint initialLiquidationPrice = usdValue_q112.sub(liquidationDiscount_q112).div(Q112); // sends liquidation command to the Vault vault.triggerLiquidation(asset, owner, initialLiquidationPrice); // fire an liquidation event emit LiquidationTriggered(asset, owner); } function getCollateralUsdValue_q112(address asset, address owner) public view returns (uint) { return IOracleUsd(oracleRegistry.oracleByAsset(asset)).assetToUsd(asset, vault.collaterals(asset, owner)); } function _ensureOracle(address asset) internal view { uint oracleType = oracleRegistry.oracleTypeByAsset(asset); require(oracleType != 0, "Unit Protocol: INVALID_ORACLE_TYPE"); address oracle = oracleRegistry.oracleByType(oracleType); require(oracle != address(0), "Unit Protocol: DISABLED_ORACLE"); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the collateral * @param owner The owner of the position * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address owner ) public view returns (bool) { uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); return _isLiquidatablePosition(asset, owner, usdValue_q112); } /** * @dev Calculates current utilization ratio * @param asset The address of the collateral * @param owner The owner of the position * @return utilization ratio **/ function utilizationRatio( address asset, address owner ) public view returns (uint) { uint debt = vault.getTotalDebt(asset, owner); if (debt == 0) return 0; uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); return debt.mul(100).mul(Q112).div(usdValue_q112); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "../interfaces/IVault.sol"; import '../interfaces/IVaultParameters.sol'; import "../interfaces/IOracleRegistry.sol"; import "../interfaces/ICDPRegistry.sol"; import '../interfaces/IToken.sol'; import "../interfaces/vault-managers/parameters/IVaultManagerParameters.sol"; import "../interfaces/vault-managers/parameters/IVaultManagerBorrowFeeParameters.sol"; import "../helpers/ReentrancyGuard.sol"; import '../helpers/TransferHelper.sol'; import "../helpers/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title BaseCDPManager * @dev all common logic should be moved here in future **/ abstract contract BaseCDPManager is ReentrancyGuard { using SafeMath for uint; IVault public immutable vault; IVaultManagerParameters public immutable vaultManagerParameters; IOracleRegistry public immutable oracleRegistry; ICDPRegistry public immutable cdpRegistry; IVaultManagerBorrowFeeParameters public immutable vaultManagerBorrowFeeParameters; IERC20 public immutable usdp; uint public constant Q112 = 2 ** 112; uint public constant DENOMINATOR_1E5 = 1e5; /** * @dev Trigger when joins are happened **/ event Join(address indexed asset, address indexed owner, uint main, uint usdp); /** * @dev Trigger when exits are happened **/ event Exit(address indexed asset, address indexed owner, uint main, uint usdp); /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed asset, address indexed owner); modifier checkpoint(address asset, address owner) { _; cdpRegistry.checkpoint(asset, owner); } /** * @param _vaultManagerParameters The address of the contract with Vault manager parameters * @param _oracleRegistry The address of the oracle registry * @param _cdpRegistry The address of the CDP registry * @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters **/ constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) { require( _vaultManagerParameters != address(0) && _oracleRegistry != address(0) && _cdpRegistry != address(0) && _vaultManagerBorrowFeeParameters != address(0), "Unit Protocol: INVALID_ARGS" ); vaultManagerParameters = IVaultManagerParameters(_vaultManagerParameters); IVault vaultLocal = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault()); vault = vaultLocal; oracleRegistry = IOracleRegistry(_oracleRegistry); cdpRegistry = ICDPRegistry(_cdpRegistry); vaultManagerBorrowFeeParameters = IVaultManagerBorrowFeeParameters(_vaultManagerBorrowFeeParameters); usdp = IERC20(vaultLocal.usdp()); } /** * @notice Charge borrow fee if needed */ function _chargeBorrowFee(address asset, address user, uint usdpAmount) internal { uint borrowFee = vaultManagerBorrowFeeParameters.calcBorrowFeeAmount(asset, usdpAmount); if (borrowFee == 0) { // very small amount case return; } // to fail with concrete reason, not with TRANSFER_FROM_FAILED from safeTransferFrom require(usdp.allowance(user, address(this)) >= borrowFee, "Unit Protocol: BORROW_FEE_NOT_APPROVED"); TransferHelper.safeTransferFrom( address(usdp), user, vaultManagerBorrowFeeParameters.feeReceiver(), borrowFee ); } // decreases debt function _repay(address asset, address owner, uint usdpAmount) internal { uint fee = vault.calculateFee(asset, owner, usdpAmount); vault.chargeFee(vault.usdp(), owner, fee); // burn USDP from the owner's balance uint debtAfter = vault.repay(asset, owner, usdpAmount); if (debtAfter == 0) { // clear unused storage vault.destroy(asset, owner); } } /** * @dev Calculates liquidation price * @param asset The address of the collateral * @param owner The owner of the position * @return Q112-encoded liquidation price **/ function liquidationPrice_q112( address asset, address owner ) external view returns (uint) { uint debt = vault.getTotalDebt(asset, owner); if (debt == 0) return uint(-1); uint collateralLiqPrice = debt.mul(100).mul(Q112).div(vaultManagerParameters.liquidationRatio(asset)); require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS"); return collateralLiqPrice / vault.collaterals(asset, owner) / 10 ** (18 - IToken(asset).decimals()); } function _calcPrincipal(address asset, address owner, uint repayment) internal view returns (uint) { uint fee = vault.stabilityFee(asset, owner) * (block.timestamp - vault.lastUpdate(asset, owner)) / 365 days; return repayment * DENOMINATOR_1E5 / (DENOMINATOR_1E5 + fee); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the collateral * @param owner The owner of the position * @param usdValue_q112 Q112-encoded USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function _isLiquidatablePosition( address asset, address owner, uint usdValue_q112 ) internal view returns (bool) { uint debt = vault.getTotalDebt(asset, owner); // position is collateralized if there is no debt if (debt == 0) return false; return debt.mul(100).mul(Q112).div(usdValue_q112) >= vaultManagerParameters.liquidationRatio(asset); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; pragma abicoder v2; interface IOracleRegistry { struct Oracle { uint oracleType; address oracleAddress; } function WETH ( ) external view returns ( address ); function getKeydonixOracleTypes ( ) external view returns ( uint256[] memory ); function getOracles ( ) external view returns ( Oracle[] memory foundOracles ); function keydonixOracleTypes ( uint256 ) external view returns ( uint256 ); function maxOracleType ( ) external view returns ( uint256 ); function oracleByAsset ( address asset ) external view returns ( address ); function oracleByType ( uint256 ) external view returns ( address ); function oracleTypeByAsset ( address ) external view returns ( uint256 ); function oracleTypeByOracle ( address ) external view returns ( uint256 ); function setKeydonixOracleTypes ( uint256[] memory _keydonixOracleTypes ) external; function setOracle ( uint256 oracleType, address oracle ) external; function setOracleTypeForAsset ( address asset, uint256 oracleType ) external; function setOracleTypeForAssets ( address[] memory assets, uint256 oracleType ) external; function unsetOracle ( uint256 oracleType ) external; function unsetOracleForAsset ( address asset ) external; function unsetOracleForAssets ( address[] memory assets ) external; function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IOracleUsd { // returns Q112-encoded value // returned value 10**18 * 2**112 is $1 function assetToUsd(address asset, uint amount) external view returns (uint); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVault { function DENOMINATOR_1E2 ( ) external view returns ( uint256 ); function DENOMINATOR_1E5 ( ) external view returns ( uint256 ); function borrow ( address asset, address user, uint256 amount ) external returns ( uint256 ); function calculateFee ( address asset, address user, uint256 amount ) external view returns ( uint256 ); function changeOracleType ( address asset, address user, uint256 newOracleType ) external; function chargeFee ( address asset, address user, uint256 amount ) external; function col ( ) external view returns ( address ); function colToken ( address, address ) external view returns ( uint256 ); function collaterals ( address, address ) external view returns ( uint256 ); function debts ( address, address ) external view returns ( uint256 ); function depositCol ( address asset, address user, uint256 amount ) external; function depositEth ( address user ) external payable; function depositMain ( address asset, address user, uint256 amount ) external; function destroy ( address asset, address user ) external; function getTotalDebt ( address asset, address user ) external view returns ( uint256 ); function lastUpdate ( address, address ) external view returns ( uint256 ); function liquidate ( address asset, address positionOwner, uint256 mainAssetToLiquidator, uint256 colToLiquidator, uint256 mainAssetToPositionOwner, uint256 colToPositionOwner, uint256 repayment, uint256 penalty, address liquidator ) external; function liquidationBlock ( address, address ) external view returns ( uint256 ); function liquidationFee ( address, address ) external view returns ( uint256 ); function liquidationPrice ( address, address ) external view returns ( uint256 ); function oracleType ( address, address ) external view returns ( uint256 ); function repay ( address asset, address user, uint256 amount ) external returns ( uint256 ); function spawn ( address asset, address user, uint256 _oracleType ) external; function stabilityFee ( address, address ) external view returns ( uint256 ); function tokenDebts ( address ) external view returns ( uint256 ); function triggerLiquidation ( address asset, address positionOwner, uint256 initialPrice ) external; function update ( address asset, address user ) external; function usdp ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); function weth ( ) external view returns ( address payable ); function withdrawCol ( address asset, address user, uint256 amount ) external; function withdrawEth ( address user, uint256 amount ) external; function withdrawMain ( address asset, address user, uint256 amount ) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; interface ICDPRegistry { struct CDP { address asset; address owner; } function batchCheckpoint ( address[] calldata assets, address[] calldata owners ) external; function batchCheckpointForAsset ( address asset, address[] calldata owners ) external; function checkpoint ( address asset, address owner ) external; function cr ( ) external view returns ( address ); function getAllCdps ( ) external view returns ( CDP[] memory r ); function getCdpsByCollateral ( address asset ) external view returns ( CDP[] memory cdps ); function getCdpsByOwner ( address owner ) external view returns ( CDP[] memory r ); function getCdpsCount ( ) external view returns ( uint256 totalCdpCount ); function getCdpsCountForCollateral ( address asset ) external view returns ( uint256 ); function isAlive ( address asset, address owner ) external view returns ( bool ); function isListed ( address asset, address owner ) external view returns ( bool ); function vault ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultManagerParameters { function devaluationPeriod ( address ) external view returns ( uint256 ); function initialCollateralRatio ( address ) external view returns ( uint256 ); function liquidationDiscount ( address ) external view returns ( uint256 ); function liquidationRatio ( address ) external view returns ( uint256 ); function maxColPercent ( address ) external view returns ( uint256 ); function minColPercent ( address ) external view returns ( uint256 ); function setColPartRange ( address asset, uint256 min, uint256 max ) external; function setCollateral ( address asset, uint256 stabilityFeeValue, uint256 liquidationFeeValue, uint256 initialCollateralRatioValue, uint256 liquidationRatioValue, uint256 liquidationDiscountValue, uint256 devaluationPeriodValue, uint256 usdpLimit, uint256[] calldata oracles, uint256 minColP, uint256 maxColP ) external; function setDevaluationPeriod ( address asset, uint256 newValue ) external; function setInitialCollateralRatio ( address asset, uint256 newValue ) external; function setLiquidationDiscount ( address asset, uint256 newValue ) external; function setLiquidationRatio ( address asset, uint256 newValue ) external; function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultParameters { function canModifyVault ( address ) external view returns ( bool ); function foundation ( ) external view returns ( address ); function isManager ( address ) external view returns ( bool ); function isOracleTypeEnabled ( uint256, address ) external view returns ( bool ); function liquidationFee ( address ) external view returns ( uint256 ); function setCollateral ( address asset, uint256 stabilityFeeValue, uint256 liquidationFeeValue, uint256 usdpLimit, uint256[] calldata oracles ) external; function setFoundation ( address newFoundation ) external; function setLiquidationFee ( address asset, uint256 newValue ) external; function setManager ( address who, bool permit ) external; function setOracleType ( uint256 _type, address asset, bool enabled ) external; function setStabilityFee ( address asset, uint256 newValue ) external; function setTokenDebtLimit ( address asset, uint256 limit ) external; function setVaultAccess ( address who, bool permit ) external; function stabilityFee ( address ) external view returns ( uint256 ); function tokenDebtLimit ( address ) external view returns ( uint256 ); function vault ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IToken { function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: division by zero"); return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultManagerBorrowFeeParameters { /** * @notice 1 = 100% = 10000 basis points **/ function BASIS_POINTS_IN_1() external view returns (uint); /** * @notice Borrow fee receiver **/ function feeReceiver() external view returns (address); /** * @notice Sets the borrow fee receiver. Only manager is able to call this function * @param newFeeReceiver The address of fee receiver **/ function setFeeReceiver(address newFeeReceiver) external; /** * @notice Sets the base borrow fee in basis points (1bp = 0.01% = 0.0001). Only manager is able to call this function * @param newBaseBorrowFeeBasisPoints The borrow fee in basis points **/ function setBaseBorrowFee(uint16 newBaseBorrowFeeBasisPoints) external; /** * @notice Sets the borrow fee for a particular collateral in basis points (1bp = 0.01% = 0.0001). Only manager is able to call this function * @param asset The address of the main collateral token * @param newEnabled Is custom fee enabled for asset * @param newFeeBasisPoints The borrow fee in basis points **/ function setAssetBorrowFee(address asset, bool newEnabled, uint16 newFeeBasisPoints) external; /** * @notice Returns borrow fee for particular collateral in basis points (1bp = 0.01% = 0.0001) * @param asset The address of the main collateral token * @return feeBasisPoints The borrow fee in basis points **/ function getBorrowFee(address asset) external view returns (uint16 feeBasisPoints); /** * @notice Returns borrow fee for usdp amount for particular collateral * @param asset The address of the main collateral token * @return The borrow fee **/ function calcBorrowFeeAmount(address asset, uint usdpAmount) external view returns (uint); } // SPDX-License-Identifier: GPL-3.0-or-later /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
Withdraws WETH and converts to ETH ethAmount ETH amount to withdraw usdpAmount The amount of USDP token to repay/
function exit_Eth(uint ethAmount, uint usdpAmount) public returns (uint) { usdpAmount = exit(WETH, ethAmount, usdpAmount); require(IWETH(WETH).transferFrom(msg.sender, address(this), ethAmount), "Unit Protocol: WETH_TRANSFER_FROM_FAILED"); IWETH(WETH).withdraw(ethAmount); require(success, "Unit Protocol: ETH_TRANSFER_FAILED"); return usdpAmount; }
2,505,551
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2020 zapper, nodar, suhail, seb, sumit, apoorv // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // ///@author Zapper ///@notice This contract moves liquidity between UniswapV2 and Balancer pools. pragma solidity ^0.5.0; 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; } } 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" ); } } } 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" ); } } contract ReentrancyGuard { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IERC20 { function decimals() external view returns (uint256); 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 ); } interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } interface IUniswapV2Pair { function token0() external pure returns (address); function token1() external pure returns (address); function getReserves() external view returns ( uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast ); // this low-level function should be called from a contract which performs important safety checks function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; // force balances to match reserves function skim(address to) external; } interface IUniswapV2ZapIn { function ZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount, uint256 _minPoolTokens ) external payable returns (uint256); } interface IUniswapV2ZapOut { function ZapOut( address _ToTokenContractAddress, address _FromUniPoolAddress, uint256 _IncomingLP, uint256 _minTokensRec ) external payable returns (uint256); } interface IBalancerZapIn { function ZapIn( address _FromTokenContractAddress, address _ToBalancerPoolAddress, uint256 _amount, uint256 _minPoolTokens ) external payable returns (uint256 tokensBought); } interface IBalancerZapOut { function EasyZapOut( address _ToTokenContractAddress, address _FromBalancerPoolAddress, uint256 _IncomingBPT, uint256 _minTokensRec ) external payable returns (uint256); } interface IBPool { function isBound(address t) external view returns (bool); } contract Balancer_UniswapV2_Pipe_V1_4 is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; bool public stopped = false; IUniswapV2Factory private constant UniSwapV2FactoryAddress = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); IBalancerZapOut public balancerZapOut; IUniswapV2ZapIn public uniswapV2ZapIn; IBalancerZapIn public balancerZapIn; IUniswapV2ZapOut public uniswapV2ZapOut; constructor( address _balancerZapIn, address _balancerZapOut, address _uniswapV2ZapIn, address _uniswapV2ZapOut ) public { balancerZapIn = IBalancerZapIn(_balancerZapIn); balancerZapOut = IBalancerZapOut(_balancerZapOut); uniswapV2ZapIn = IUniswapV2ZapIn(_uniswapV2ZapIn); uniswapV2ZapOut = IUniswapV2ZapOut(_uniswapV2ZapOut); } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } function PipeBalancerUniV2( address _FromBalancerPoolAddress, uint256 _IncomingBPT, address _toUniswapPoolAddress, address _toWhomToIssue, uint256 _minUniV2Tokens ) public nonReentrant stopInEmergency returns (uint256) { // Get BPT IERC20(_FromBalancerPoolAddress).safeTransferFrom( msg.sender, address(this), _IncomingBPT ); // Approve BalUnZap IERC20(_FromBalancerPoolAddress).safeApprove( address(balancerZapOut), _IncomingBPT ); // Get pair addresses from UniV2Pair address token0 = IUniswapV2Pair(_toUniswapPoolAddress).token0(); address token1 = IUniswapV2Pair(_toUniswapPoolAddress).token1(); address zapOutToToken = address(0); if (IBPool(_FromBalancerPoolAddress).isBound(token0)) { zapOutToToken = token0; } else if (IBPool(_FromBalancerPoolAddress).isBound(token1)) { zapOutToToken = token1; } // ZapOut from Balancer uint256 zappedOutAmt = balancerZapOut.EasyZapOut( zapOutToToken, _FromBalancerPoolAddress, _IncomingBPT, 0 ); uint256 LPTBought; if (zapOutToToken == address(0)) { // use ETH to ZapIn to UNIV2 LPTBought = uniswapV2ZapIn.ZapIn.value(zappedOutAmt)( _toWhomToIssue, address(0), token0, token1, 0, _minUniV2Tokens ); } else { IERC20(zapOutToToken).safeApprove( address(uniswapV2ZapIn), IERC20(zapOutToToken).balanceOf(address(this)) ); LPTBought = uniswapV2ZapIn.ZapIn.value(0)( _toWhomToIssue, zapOutToToken, token0, token1, zappedOutAmt, _minUniV2Tokens ); } return LPTBought; } function PipeUniV2Balancer( address _FromUniswapPoolAddress, uint256 _IncomingLPT, address _ToBalancerPoolAddress, address _toWhomToIssue, uint256 _minBPTokens ) public nonReentrant stopInEmergency returns (uint256) { // Get LPT IERC20(_FromUniswapPoolAddress).safeTransferFrom( msg.sender, address(this), _IncomingLPT ); // Approve UniUnZap IERC20(_FromUniswapPoolAddress).safeApprove( address(uniswapV2ZapOut), _IncomingLPT ); // Get pair addresses from UniV2Pair address token0 = IUniswapV2Pair(_FromUniswapPoolAddress).token0(); address token1 = IUniswapV2Pair(_FromUniswapPoolAddress).token1(); address zapOutToToken = address(0); if (IBPool(_ToBalancerPoolAddress).isBound(token0)) { zapOutToToken = token0; } else if (IBPool(_ToBalancerPoolAddress).isBound(token1)) { zapOutToToken = token1; } // ZapOut from Uni uint256 tokensRec = uniswapV2ZapOut.ZapOut( zapOutToToken, _FromUniswapPoolAddress, _IncomingLPT, 0 ); // ZapIn to Balancer uint256 BPTBought; if (zapOutToToken == address(0)) { // use ETH to ZapIn to Balancer BPTBought = balancerZapIn.ZapIn.value(tokensRec)( address(0), _ToBalancerPoolAddress, 0, _minBPTokens ); } else { IERC20(zapOutToToken).safeApprove(address(balancerZapIn), tokensRec); BPTBought = balancerZapIn.ZapIn.value(0)( zapOutToToken, _ToBalancerPoolAddress, tokensRec, _minBPTokens ); } IERC20(_ToBalancerPoolAddress).safeTransfer(_toWhomToIssue, BPTBought); return BPTBought; } // Zap Contract Setters function setbalancerZapIn(address _balancerZapIn) public onlyOwner { balancerZapIn = IBalancerZapIn(_balancerZapIn); } function setBalancerZapOut(address _balancerZapOut) public onlyOwner { balancerZapOut = IBalancerZapOut(_balancerZapOut); } function setUniswapV2ZapIn(address _uniswapV2ZapIn) public onlyOwner { uniswapV2ZapIn = IUniswapV2ZapIn(_uniswapV2ZapIn); } function setUniswapV2ZapOut(address _uniswapV2ZapOut) public onlyOwner { uniswapV2ZapOut = IUniswapV2ZapOut(_uniswapV2ZapOut); } // fallback to receive ETH function() external payable {} function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner { uint256 qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(owner(), qty); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } // - to withdraw any ETH balance sitting in the contract function withdraw() public onlyOwner { uint256 contractBalance = address(this).balance; address payable _to = owner().toPayable(); Address.sendValue(_to, contractBalance); } }
Get LPT Approve UniUnZap Get pair addresses from UniV2Pair use ETH to ZapIn to Balancer
function PipeUniV2Balancer( address _FromUniswapPoolAddress, uint256 _IncomingLPT, address _ToBalancerPoolAddress, address _toWhomToIssue, uint256 _minBPTokens ) public nonReentrant stopInEmergency returns (uint256) { IERC20(_FromUniswapPoolAddress).safeTransferFrom( msg.sender, address(this), _IncomingLPT ); IERC20(_FromUniswapPoolAddress).safeApprove( address(uniswapV2ZapOut), _IncomingLPT ); address token0 = IUniswapV2Pair(_FromUniswapPoolAddress).token0(); address token1 = IUniswapV2Pair(_FromUniswapPoolAddress).token1(); address zapOutToToken = address(0); if (IBPool(_ToBalancerPoolAddress).isBound(token0)) { zapOutToToken = token0; zapOutToToken = token1; } zapOutToToken, _FromUniswapPoolAddress, _IncomingLPT, 0 ); if (zapOutToToken == address(0)) { BPTBought = balancerZapIn.ZapIn.value(tokensRec)( address(0), _ToBalancerPoolAddress, 0, _minBPTokens ); IERC20(zapOutToToken).safeApprove(address(balancerZapIn), tokensRec); BPTBought = balancerZapIn.ZapIn.value(0)( zapOutToToken, _ToBalancerPoolAddress, tokensRec, _minBPTokens ); } IERC20(_ToBalancerPoolAddress).safeTransfer(_toWhomToIssue, BPTBought); return BPTBought; }
12,044,775
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; contract BTRST { /// @notice EIP-20 token name for this token string public constant name = "BTRST"; /// @notice EIP-20 token symbol for this token string public constant symbol = "BTRST"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 250000000e18; // 250 million BTRST /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new BTRST token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @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 rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "BTRST::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @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 rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "BTRST::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "BTRST::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "BTRST::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "BTRST::delegateBySig: invalid nonce"); require(now <= expiry, "BTRST::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "BTRST::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "BTRST::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "BTRST::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "BTRST::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "BTRST::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "BTRST::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "BTRST::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "BTRST::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
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, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "BTRST::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; }
6,694,442
// File: contracts/Dependencies/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/proxy/Dependencies/Ownable.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 { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Dependencies/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: contracts/Dependencies/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/Dependencies/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value : value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/Dependencies/SafeERC20.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"); } } } // File: contracts/Dependencies/IERC165.sol /** * @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/Dependencies/IERC721.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; } // File: contracts/Dependencies/ReentrancyGuard.sol /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * 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; } } // File: contracts/proxy/Sales721.sol contract Sales721 is Ownable, ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; uint private saleIDCounter; bool private onlyInitOnce; struct BaseSale { // the sale setter address seller; // addresses of token to sell address[] tokenAddresses; // tokenIDs of token to sell uint[] tokenIDs; // address of token to pay address payTokenAddress; // price of token to pay uint price; // address of receiver address receiver; uint startTime; uint endTime; // whether the sale is available bool isAvailable; } struct FlashSale { BaseSale base; // max number of token could be bought from an address uint purchaseLimitation; } struct Auction { BaseSale base; // the minimum increment in a bid uint minBidIncrement; // the highest price so far uint highestBidPrice; // the highest bidder so far address highestBidder; } // whitelist to set sale mapping(address => bool) public whitelist; // sale ID -> flash sale mapping(uint => FlashSale) flashSales; // sale ID -> mapping(address => how many tokens have bought) mapping(uint => mapping(address => uint)) flashSaleIDToPurchaseRecord; // sale ID -> auction mapping(uint => Auction) auctions; // filter to check repetition mapping(address => mapping(uint => bool)) repetitionFilter; event SetWhitelist(address _member, bool _isAdded); event SetFlashSale(uint _saleID, address _flashSaleSetter, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _endTime); event UpdateFlashSale(uint _saleID, address _operator, address[] _newTokenAddresses, uint[] _newTokenIDs, address _newPayTokenAddress, uint _newPrice, address _newReceiver, uint _newPurchaseLimitation, uint _newStartTime, uint _newEndTime); event CancelFlashSale(uint _saleID, address _operator); event FlashSaleExpired(uint _saleID, address _operator); event Purchase(uint _saleID, address _buyer, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _totalPayment); event SetAuction(uint _saleID, address _auctionSetter, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _endTime); event UpdateAuction(uint _saleID, address _operator, address[] _newTokenAddresses, uint[] _newTokenIDs, address _newPayTokenAddress, uint _newInitialPrice, address _newReceiver, uint _newMinBidIncrement, uint _newStartTime, uint _newEndTime); event RefundToPreviousBidder(uint _saleID, address _previousBidder, address _payTokenAddress, uint _refundAmount); event CancelAuction(uint _saleID, address _operator); event NewBidderTransfer(uint _saleID, address _newBidder, address _payTokenAddress, uint _bidPrice); event SettleAuction(uint _saleID, address _operator, address _receiver, address _highestBidder, address[] _tokenAddresses, uint[] _tokenIDs, address _payTokenAddress, uint _highestBidPrice); modifier onlyWhitelist() { require(whitelist[msg.sender], "the caller isn't in the whitelist"); _; } function init(address _newOwner) public { require(!onlyInitOnce, "already initialized"); _transferOwnership(_newOwner); onlyInitOnce = true; } function setWhitelist(address _member, bool _status) external onlyOwner { whitelist[_member] = _status; emit SetWhitelist(_member, _status); } // set auction by the member in whitelist function setAuction( address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { // 1. check the validity of params _checkAuctionParams(msg.sender, _tokenAddresses, _tokenIDs, _initialPrice, _minBidIncrement, _startTime, _duration); // 2. build auction Auction memory auction = Auction({ base : BaseSale({ seller : msg.sender, tokenAddresses : _tokenAddresses, tokenIDs : _tokenIDs, payTokenAddress : _payTokenAddress, price : _initialPrice, receiver : _receiver, startTime : _startTime, endTime : _startTime.add(_duration), isAvailable : true }), minBidIncrement : _minBidIncrement, highestBidPrice : 0, highestBidder : address(0) }); // 3. store auction uint currentSaleID = saleIDCounter; saleIDCounter = saleIDCounter.add(1); auctions[currentSaleID] = auction; emit SetAuction(currentSaleID, auction.base.seller, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.base.price, auction.base.receiver, auction.minBidIncrement, auction.base.startTime, auction.base.endTime); } // update auction by the member in whitelist function updateAuction( uint _saleID, address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _initialPrice, address _receiver, uint _minBidIncrement, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); // 1. make sure that the auction doesn't start require(auction.base.startTime > now, "it's not allowed to update the auction after the start of it"); require(auction.base.isAvailable, "the auction has been cancelled"); require(auction.base.seller == msg.sender, "the auction can only be updated by its setter"); // 2. check the validity of params to update _checkAuctionParams(msg.sender, _tokenAddresses, _tokenIDs, _initialPrice, _minBidIncrement, _startTime, _duration); // 3. update the auction auction.base.tokenAddresses = _tokenAddresses; auction.base.tokenIDs = _tokenIDs; auction.base.payTokenAddress = _payTokenAddress; auction.base.price = _initialPrice; auction.base.receiver = _receiver; auction.base.startTime = _startTime; auction.base.endTime = _startTime.add(_duration); auction.minBidIncrement = _minBidIncrement; auctions[_saleID] = auction; emit UpdateAuction(_saleID, auction.base.seller, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.base.price, auction.base.receiver, auction.minBidIncrement, auction.base.startTime, auction.base.endTime); } // cancel the auction function cancelAuction(uint _saleID) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); require(auction.base.isAvailable, "the auction isn't available"); require(auction.base.seller == msg.sender, "the auction can only be cancelled by its setter"); if (auction.highestBidPrice != 0) { // some bid has paid for this auction IERC20(auction.base.payTokenAddress).safeTransfer(auction.highestBidder, auction.highestBidPrice); emit RefundToPreviousBidder(_saleID, auction.highestBidder, auction.base.payTokenAddress, auction.highestBidPrice); } auctions[_saleID].base.isAvailable = false; emit CancelAuction(_saleID, msg.sender); } // bid for the target auction function bid(uint _saleID, uint _bidPrice) external nonReentrant { Auction memory auction = _getAuctionByID(_saleID); // check the validity of the target auction require(auction.base.isAvailable, "the auction isn't available"); require(auction.base.seller != msg.sender, "the setter can't bid for its own auction"); uint currentTime = now; require(currentTime >= auction.base.startTime, "the auction doesn't start"); require(currentTime < auction.base.endTime, "the auction has expired"); IERC20 payToken = IERC20(auction.base.payTokenAddress); // check bid price in auction if (auction.highestBidPrice != 0) { // not first bid require(_bidPrice.sub(auction.highestBidPrice) >= auction.minBidIncrement, "the bid price must be larger than the sum of current highest one and minimum bid increment"); // refund to the previous highest bidder from this contract payToken.safeTransfer(auction.highestBidder, auction.highestBidPrice); emit RefundToPreviousBidder(_saleID, auction.highestBidder, auction.base.payTokenAddress, auction.highestBidPrice); } else { // first bid require(_bidPrice == auction.base.price, "first bid must follow the initial price set in the auction"); } // update storage auctions auctions[_saleID].highestBidPrice = _bidPrice; auctions[_saleID].highestBidder = msg.sender; // transfer the bid price into this contract payToken.safeApprove(address(this), 0); payToken.safeApprove(address(this), _bidPrice); payToken.safeTransferFrom(msg.sender, address(this), _bidPrice); emit NewBidderTransfer(_saleID, msg.sender, auction.base.payTokenAddress, _bidPrice); } // settle the auction by the member in whitelist function settleAuction(uint _saleID) external nonReentrant onlyWhitelist { Auction memory auction = _getAuctionByID(_saleID); // check the validity of the target auction require(auction.base.isAvailable, "only the available auction can be settled"); require(auction.base.endTime <= now, "the auction can only be settled after its end time"); if (auction.highestBidPrice != 0) { // the auction has been bidden // transfer pay token to the receiver from this contract IERC20(auction.base.payTokenAddress).safeTransfer(auction.base.receiver, auction.highestBidPrice); // transfer erc721s to the bidder who keeps the highest price for (uint i = 0; i < auction.base.tokenAddresses.length; i++) { IERC721(auction.base.tokenAddresses[i]).safeTransferFrom(auction.base.seller, auction.highestBidder, auction.base.tokenIDs[i]); } } // close the auction auctions[_saleID].base.isAvailable = false; emit SettleAuction(_saleID, msg.sender, auction.base.receiver, auction.highestBidder, auction.base.tokenAddresses, auction.base.tokenIDs, auction.base.payTokenAddress, auction.highestBidPrice); } // set flash sale by the member in whitelist // NOTE: set 0 duration if you don't want an endTime function setFlashSale( address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { // 1. check the validity of params _checkFlashSaleParams(msg.sender, _tokenAddresses, _tokenIDs, _price, _startTime, _purchaseLimitation); // 2. build flash sale uint endTime; if (_duration != 0) { endTime = _startTime.add(_duration); } FlashSale memory flashSale = FlashSale({ base : BaseSale({ seller : msg.sender, tokenAddresses : _tokenAddresses, tokenIDs : _tokenIDs, payTokenAddress : _payTokenAddress, price : _price, receiver : _receiver, startTime : _startTime, endTime : endTime, isAvailable : true }), purchaseLimitation : _purchaseLimitation }); // 3. store flash sale uint currentSaleID = saleIDCounter; saleIDCounter = saleIDCounter.add(1); flashSales[currentSaleID] = flashSale; emit SetFlashSale(currentSaleID, flashSale.base.seller, flashSale.base.tokenAddresses, flashSale.base.tokenIDs, flashSale.base.payTokenAddress, flashSale.base.price, flashSale.base.receiver, flashSale.purchaseLimitation, flashSale.base.startTime, flashSale.base.endTime); } // update the flash sale before starting // NOTE: set 0 duration if you don't want an endTime function updateFlashSale( uint _saleID, address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { FlashSale memory flashSale = _getFlashSaleByID(_saleID); // 1. make sure that the flash sale doesn't start require(flashSale.base.startTime > now, "it's not allowed to update the flash sale after the start of it"); require(flashSale.base.isAvailable, "the flash sale has been cancelled"); require(flashSale.base.seller == msg.sender, "the flash sale can only be updated by its setter"); // 2. check the validity of params to update _checkFlashSaleParams(msg.sender, _tokenAddresses, _tokenIDs, _price, _startTime, _purchaseLimitation); // 3. update flash sale uint endTime; if (_duration != 0) { endTime = _startTime.add(_duration); } flashSale.base.tokenAddresses = _tokenAddresses; flashSale.base.tokenIDs = _tokenIDs; flashSale.base.payTokenAddress = _payTokenAddress; flashSale.base.price = _price; flashSale.base.receiver = _receiver; flashSale.base.startTime = _startTime; flashSale.base.endTime = endTime; flashSale.purchaseLimitation = _purchaseLimitation; flashSales[_saleID] = flashSale; emit UpdateFlashSale(_saleID, flashSale.base.seller, flashSale.base.tokenAddresses, flashSale.base.tokenIDs, flashSale.base.payTokenAddress, flashSale.base.price, flashSale.base.receiver, flashSale.purchaseLimitation, flashSale.base.startTime, flashSale.base.endTime); } // cancel the flash sale function cancelFlashSale(uint _saleID) external onlyWhitelist { FlashSale memory flashSale = _getFlashSaleByID(_saleID); require(flashSale.base.isAvailable, "the flash sale isn't available"); require(flashSale.base.seller == msg.sender, "the flash sale can only be cancelled by its setter"); flashSales[_saleID].base.isAvailable = false; emit CancelFlashSale(_saleID, msg.sender); } // rush to purchase by anyone function purchase(uint _saleID, uint _amount) external nonReentrant { FlashSale memory flashSale = _getFlashSaleByID(_saleID); // check the validity require(_amount > 0, "amount should be > 0"); require(flashSale.base.isAvailable, "the flash sale isn't available"); require(flashSale.base.seller != msg.sender, "the setter can't make a purchase from its own flash sale"); uint currentTime = now; require(currentTime >= flashSale.base.startTime, "the flash sale doesn't start"); // check whether the end time arrives if (flashSale.base.endTime != 0 && flashSale.base.endTime <= currentTime) { // the flash sale has been set an end time and expired flashSales[_saleID].base.isAvailable = false; emit FlashSaleExpired(_saleID, msg.sender); return; } // check the purchase record of the buyer uint newPurchaseRecord = flashSaleIDToPurchaseRecord[_saleID][msg.sender].add(_amount); require(newPurchaseRecord <= flashSale.purchaseLimitation, "total amount to purchase exceeds the limitation of an address"); // check whether the amount of token rest in flash sale is sufficient for this trade require(_amount <= flashSale.base.tokenIDs.length, "insufficient amount of token for this trade"); // pay the receiver flashSaleIDToPurchaseRecord[_saleID][msg.sender] = newPurchaseRecord; uint totalPayment = flashSale.base.price.mul(_amount); IERC20(flashSale.base.payTokenAddress).safeTransferFrom(msg.sender, flashSale.base.receiver, totalPayment); // transfer erc721 tokens to buyer address[] memory tokenAddressesRecord = new address[](_amount); uint[] memory tokenIDsRecord = new uint[](_amount); uint targetIndex = flashSale.base.tokenIDs.length - 1; for (uint i = 0; i < _amount; i++) { IERC721(flashSale.base.tokenAddresses[targetIndex]).safeTransferFrom(flashSale.base.seller, msg.sender, flashSale.base.tokenIDs[targetIndex]); tokenAddressesRecord[i] = flashSale.base.tokenAddresses[targetIndex]; tokenIDsRecord[i] = flashSale.base.tokenIDs[targetIndex]; targetIndex--; flashSales[_saleID].base.tokenAddresses.pop(); flashSales[_saleID].base.tokenIDs.pop(); } if (flashSales[_saleID].base.tokenAddresses.length == 0) { flashSales[_saleID].base.isAvailable = false; } emit Purchase(_saleID, msg.sender, tokenAddressesRecord, tokenIDsRecord, flashSale.base.payTokenAddress, totalPayment); } function getFlashSaleTokenRemaining(uint _saleID) public view returns (uint){ // check whether the flash sale ID exists FlashSale memory flashSale = _getFlashSaleByID(_saleID); return flashSale.base.tokenIDs.length; } function getFlashSalePurchaseRecord(uint _saleID, address _buyer) public view returns (uint){ // check whether the flash sale ID exists _getFlashSaleByID(_saleID); return flashSaleIDToPurchaseRecord[_saleID][_buyer]; } function getAuction(uint _saleID) public view returns (Auction memory){ return _getAuctionByID(_saleID); } function getFlashSale(uint _saleID) public view returns (FlashSale memory){ return _getFlashSaleByID(_saleID); } function _getAuctionByID(uint _saleID) internal view returns (Auction memory auction){ auction = auctions[_saleID]; require(auction.base.seller != address(0), "the target auction doesn't exist"); } function _getFlashSaleByID(uint _saleID) internal view returns (FlashSale memory flashSale){ flashSale = flashSales[_saleID]; require(flashSale.base.seller != address(0), "the target flash sale doesn't exist"); } function _checkAuctionParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _initialPrice, uint _minBidIncrement, uint _startTime, uint _duration ) internal { _checkBaseSaleParams(_baseSaleSetter, _tokenAddresses, _tokenIDs, _initialPrice, _startTime); require(_minBidIncrement > 0, "minBidIncrement must be > 0"); require(_duration > 0, "duration must be > 0"); } function _checkFlashSaleParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _price, uint _startTime, uint _purchaseLimitation ) internal { uint standardLen = _checkBaseSaleParams(_baseSaleSetter, _tokenAddresses, _tokenIDs, _price, _startTime); require(_purchaseLimitation > 0, "purchaseLimitation must be > 0"); require(_purchaseLimitation <= standardLen, "purchaseLimitation must be <= the length of tokenAddresses"); } function _checkBaseSaleParams( address _baseSaleSetter, address[] memory _tokenAddresses, uint[] memory _tokenIDs, uint _price, uint _startTime ) internal returns (uint standardLen){ standardLen = _tokenAddresses.length; require(standardLen > 0, "length of tokenAddresses must be > 0"); require(standardLen == _tokenIDs.length, "length of tokenIDs is wrong"); // check whether the sale setter has the target tokens && approval IERC721 tokenAddressCached; uint tokenIDCached; for (uint i = 0; i < standardLen; i++) { tokenAddressCached = IERC721(_tokenAddresses[i]); tokenIDCached = _tokenIDs[i]; // check repetition require(!repetitionFilter[address(tokenAddressCached)][tokenIDCached], "repetitive ERC721 tokens"); repetitionFilter[address(tokenAddressCached)][tokenIDCached] = true; require(tokenAddressCached.ownerOf(tokenIDCached) == _baseSaleSetter, "unmatched ownership of target ERC721 token"); require( tokenAddressCached.getApproved(tokenIDCached) == address(this) || tokenAddressCached.isApprovedForAll(_baseSaleSetter, address(this)), "the contract hasn't been approved for ERC721 transferring"); } require(_price > 0, "the price or the initial price must be > 0"); require(_startTime >= now, "startTime must be >= now"); // clear filter for (uint i = 0; i < standardLen; i++) { repetitionFilter[_tokenAddresses[i]][_tokenIDs[i]] = false; } } }
update the flash sale before starting NOTE: set 0 duration if you don't want an endTime 1. make sure that the flash sale doesn't start 2. check the validity of params to update 3. update flash sale
function updateFlashSale( uint _saleID, address[] memory _tokenAddresses, uint[] memory _tokenIDs, address _payTokenAddress, uint _price, address _receiver, uint _purchaseLimitation, uint _startTime, uint _duration ) external nonReentrant onlyWhitelist { FlashSale memory flashSale = _getFlashSaleByID(_saleID); require(flashSale.base.startTime > now, "it's not allowed to update the flash sale after the start of it"); require(flashSale.base.isAvailable, "the flash sale has been cancelled"); require(flashSale.base.seller == msg.sender, "the flash sale can only be updated by its setter"); _checkFlashSaleParams(msg.sender, _tokenAddresses, _tokenIDs, _price, _startTime, _purchaseLimitation); uint endTime; if (_duration != 0) { endTime = _startTime.add(_duration); } flashSale.base.tokenAddresses = _tokenAddresses; flashSale.base.tokenIDs = _tokenIDs; flashSale.base.payTokenAddress = _payTokenAddress; flashSale.base.price = _price; flashSale.base.receiver = _receiver; flashSale.base.startTime = _startTime; flashSale.base.endTime = endTime; flashSale.purchaseLimitation = _purchaseLimitation; flashSales[_saleID] = flashSale; emit UpdateFlashSale(_saleID, flashSale.base.seller, flashSale.base.tokenAddresses, flashSale.base.tokenIDs, flashSale.base.payTokenAddress, flashSale.base.price, flashSale.base.receiver, flashSale.purchaseLimitation, flashSale.base.startTime, flashSale.base.endTime); }
6,053,693
./partial_match/42/0x1513554997d7A7E21B4c8a3b32d8AE95fEb63571/sources/HarvestBridgeStrategy.sol
Returns the total invested amount./
function investedUnderlyingBalance(address strategy) view public returns (uint256) { return IStrategy(strategy).investedUnderlyingBalance(); }
8,995,759
./partial_match/1/0xe80bF394d190851E215D5F67B67f8F5A52783F1E/sources/src/lib/DutchDecayLib.sol
returns a decayed output array using the given dutch spec and times outputs The output array to decay decayStartTime The time to start decaying decayEndTime The time to end decaying return result a decayed output array
function decay(DutchOutput[] memory outputs, uint256 decayStartTime, uint256 decayEndTime) internal view returns (OutputToken[] memory result) { uint256 outputLength = outputs.length; result = new OutputToken[](outputLength); unchecked { for (uint256 i = 0; i < outputLength; i++) { result[i] = decay(outputs[i], decayStartTime, decayEndTime); } } }
15,598,654
./partial_match/56/0x31974c8cC964E5D4506d97390DF2e9fF4548Fb4f/sources/MasterChef.sol
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()].BAL(amount, 'BEP20: burn amount exceeds allowance')); }
11,040,754
pragma solidity 0.4.26; import "./LiquidityPoolV2Converter.sol"; import "./interfaces/IPoolTokensContainer.sol"; import "../../interfaces/ITypedConverterFactory.sol"; /* LiquidityPoolV2Converter Factory */ contract LiquidityPoolV2ConverterFactory is ITypedConverterFactory { /** * @dev returns the converter type the factory is associated with * * @return converter type */ function converterType() public pure returns (uint16) { return 2; } /** * @dev creates a new converter with the given arguments and transfers * the ownership to the caller * * @param _anchor anchor governed by the converter * @param _registry address of a contract registry contract * @param _maxConversionFee maximum conversion fee, represented in ppm * * @return new converter */ function createConverter(IConverterAnchor _anchor, IContractRegistry _registry, uint32 _maxConversionFee) public returns (IConverter) { ConverterBase converter = new LiquidityPoolV2Converter(IPoolTokensContainer(_anchor), _registry, _maxConversionFee); converter.transferOwnership(msg.sender); return converter; } }
returns the converter type the factory is associated with return converter type/
function converterType() public pure returns (uint16) { return 2; }
1,081,549
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../interfaces/IYearnVault.sol"; import "../libraries/Authorizable.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/ITranche.sol"; contract ZapYearnShares is Authorizable { // Store the accessibility state of the contract bool public isFrozen = false; // Tranche factory address for Tranche contract address derivation address internal immutable _trancheFactory; // Tranche bytecode hash for Tranche contract address derivation. // This is constant as long as Tranche does not implement non-constant constructor arguments. bytes32 internal immutable _trancheBytecodeHash; /// @param __trancheFactory Address of the TrancheFactory contract /// @param __trancheBytecodeHash Hash of the Tranche bytecode. constructor(address __trancheFactory, bytes32 __trancheBytecodeHash) Authorizable() { _authorize(msg.sender); _trancheFactory = __trancheFactory; _trancheBytecodeHash = __trancheBytecodeHash; } /// @dev Requires that the contract is not frozen modifier notFrozen() { require(!isFrozen, "Contract frozen"); _; } /// @dev Allows an authorized address to freeze or unfreeze this contract /// @param _newState True for frozen and false for unfrozen function setIsFrozen(bool _newState) external onlyAuthorized { isFrozen = _newState; } /// @notice Mints a Principal/Interest token pair from yearn vault shares. /// then returns the tokens to the caller. /// @param _underlying The underlying ERC20 token contract of the yearn vault. /// @param _vault The address of the target yearn vault. /// @param _amount The amount of yearn shares to turn into tokens /// @param _expiration The expiration time of the Tranche contract. /// @param _position The contract which manages pooled deposits. /// @param _ptExpected The minimum amount of principal tokens to mint. /// @return returns the minted amounts of principal and yield tokens (PT and YT) function zapSharesIn( IERC20 _underlying, IYearnVault _vault, uint256 _amount, uint256 _expiration, address _position, uint256 _ptExpected ) external notFrozen returns (uint256, uint256) { _vault.transferFrom(msg.sender, address(this), _amount); _vault.withdraw(_amount, _position, 0); ITranche tranche = _deriveTranche(address(_position), _expiration); uint256 balance = _underlying.balanceOf(_position); (uint256 ptMinted, uint256 ytMinted) = tranche.prefundedDeposit( msg.sender ); require(ytMinted >= balance, "Not enough YT minted"); require(ptMinted >= _ptExpected, "Not enough PT minted"); return (ptMinted, ytMinted); } /// @dev This internal function produces the deterministic create2 /// address of the Tranche contract from a wrapped position contract and expiration /// @param _position The wrapped position contract address /// @param _expiration The expiration time of the tranche /// @return The derived Tranche contract function _deriveTranche(address _position, uint256 _expiration) internal view virtual returns (ITranche) { bytes32 salt = keccak256(abi.encodePacked(_position, _expiration)); bytes32 addressBytes = keccak256( abi.encodePacked( bytes1(0xff), _trancheFactory, salt, _trancheBytecodeHash ) ); return ITranche(address(uint160(uint256(addressBytes)))); } /// @dev This contract can hold yearn vault share allowances for addresses so if it is deprecated /// it should be removed so that users do not have to remove allowances. /// Note - onlyOwner is a stronger check than onlyAuthorized, many addresses can be /// authorized to freeze or unfreeze the contract but only the owner address can kill function deprecate() external onlyOwner { selfdestruct(payable(msg.sender)); } }
This contract can hold yearn vault share allowances for addresses so if it is deprecated it should be removed so that users do not have to remove allowances. Note - onlyOwner is a stronger check than onlyAuthorized, many addresses can be authorized to freeze or unfreeze the contract but only the owner address can kill
function deprecate() external onlyOwner { selfdestruct(payable(msg.sender)); }
916,578
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../interfaces/IEmiswap.sol"; library EmiswapLib { using SafeMath for uint256; function previewSwapExactTokenForToken(address factory, address tokenFrom, address tokenTo, uint256 ammountFrom) internal view returns(uint256 ammountTo) { IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(tokenFrom), IERC20(tokenTo)); if (pairContract != IEmiswap(0)) { ammountTo = pairContract.getReturn(IERC20(tokenFrom), IERC20(tokenTo), ammountFrom); } } /************************************************************************************** * get preview result of virtual swap by route of tokens **************************************************************************************/ function previewSwapbyRoute(address factory, address[] memory path, uint256 ammountFrom) internal view returns(uint256 ammountTo) { for (uint i=0; i < path.length - 1; i++) { if (path.length >= 2) { ammountTo = previewSwapExactTokenForToken(factory, path[i], path[i+1], ammountFrom); if (i == (path.length - 2)) { return(ammountTo); } else { ammountFrom = ammountTo; } } } } function fee(address factory) internal view returns(uint256){ return IEmiswap(factory).fee(); } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(address factory, uint256 amountOut, uint256 reserveIn, uint256 reserveOut) internal view returns (uint amountIn) { require(amountOut > 0, "EmiswapLibrary: INSUFFICIENT_OUTPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "EmiswapLibrary: INSUFFICIENT_LIQUIDITY"); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(uint256(1000000000000000000).sub(fee(factory)).div(1e15)); // 997 amountIn = (numerator / denominator).add(1); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(address factory, uint256 amountIn, uint256 reserveIn, uint256 reserveOut) internal view returns (uint amountOut) { require(amountIn > 0, "EmiswapLibrary: INSUFFICIENT_INPUT_AMOUNT"); require(reserveIn > 0 && reserveOut > 0, "EmiswapLibrary: INSUFFICIENT_LIQUIDITY"); uint256 amountInWithFee = amountIn.mul( uint256(1000000000000000000).sub(fee(factory)).div(1e15) ); //997 uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint256 amountOut, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "EmiswapLibrary: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(IERC20(path[i])), IERC20(path[i - 1])); uint256 reserveIn = IEmiswap(pairContract).getBalanceForAddition(IERC20(path[i - 1])); uint256 reserveOut = IEmiswap(pairContract).getBalanceForRemoval(IERC20(path[i])); amounts[i - 1] = getAmountIn(factory, amounts[i], reserveIn, reserveOut); } } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint256 amountIn, address[] memory path) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "EmiswapLibrary: INVALID_PATH"); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint256 i = 0; i < path.length - 1; i++) { IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(IERC20(path[i])), IERC20(path[i + 1])); uint256 reserveIn = IEmiswap(pairContract).getBalanceForAddition( IERC20( path[i] ) ); uint256 reserveOut = IEmiswap(pairContract).getBalanceForRemoval(IERC20(path[i + 1])); amounts[i + 1] = getAmountOut(factory, amounts[i], reserveIn, reserveOut); } } // 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, "EmiswapLibrary: INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "EmiswapLibrary: INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } }
get preview result of virtual swap by route of tokens/
function previewSwapbyRoute(address factory, address[] memory path, uint256 ammountFrom) internal view returns(uint256 ammountTo) { for (uint i=0; i < path.length - 1; i++) { if (path.length >= 2) { ammountTo = previewSwapExactTokenForToken(factory, path[i], path[i+1], ammountFrom); if (i == (path.length - 2)) { return(ammountTo); ammountFrom = ammountTo; } } } }
1,757,165
pragma solidity ^0.4.24; contract RSEvents { // 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 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 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 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 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); } contract modularRatScam is RSEvents {} contract RatScam is modularRatScam { using SafeMath for *; using NameFilter for string; using RSKeysCalc for uint256; RatBookInterface constant private RatBook = RatBookInterface(0x3257d637B8977781B4f8178365858A474b2A6195); string constant public name = "RatScam In One Hour"; string constant public symbol = "RS"; uint256 private rndGap_ = 0; uint256 private rndInit_ = 1 hours; // round timer starts at this uint256 private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 private rndMax_ = 1 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** address private adminAddress; 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 => RSdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => RSdatasets.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 //**************** //RSdatasets.Round public round_; // round data mapping (uint256 => RSdatasets.Round) public round_; // (rID => data) round data //**************** // TEAM FEE DATA //**************** uint256 public fees_ = 60; // fee distribution uint256 public potSplit_ = 45; // pot split distribution //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { adminAddress = msg.sender; } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet"); _; } /** * @dev prevents contracts from interacting with ratscam */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "non smart contract address only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "too little money"); require(_eth <= 100000000000000000000000, "too much money"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (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 RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, _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 */ function buyXid(uint256 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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 buyCore(_pID, _affCode, _eventData_); } function buyXaddr(address _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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 buyCore(_pID, _affID, _eventData_); } function buyXname(bytes32 _affCode) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RSdatasets.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 buyCore(_pID, _affID, _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 _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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 reLoadCore(_pID, _affCode, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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 reLoadCore(_pID, _affID, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RSdatasets.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 reLoadCore(_pID, _affID, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data RSdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit RSEvents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = RatBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.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) = RatBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.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) = RatBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now)); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return total keys * @return time ends * @return time started * @return current pot * @return current player ID in lead * @return current player in leads address * @return current player in leads name * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[rID_].keys, //0 round_[rID_].end, //1 round_[rID_].strt, //2 round_[rID_].pot, //3 round_[rID_].plyr, //4 plyr_[round_[rID_].plyr].addr, //5 plyr_[round_[rID_].plyr].name, //6 airDropTracker_ + (airDropPot_ * 1000) //7 ); } /** * @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, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound 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 RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } _rID = rID_; core(_rID, _pID, msg.value, _affID, _eventData_); } /** * @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, RSdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is end, fire endRound 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 RSEvents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount ); } // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core( _rID, _pID, _eth, _affID, _eventData_); } /** * @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, RSdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 10000000000000000000) { uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 1 prize was won _eventData_.compressedData += 100000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rID) private view returns(uint256) { return((((round_[_rID].mask).mul(plyrRnds_[_pID][_rID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rID].mask)); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _eth) public view returns(uint256) { uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(RatBook), "only RatBook can call this function"); 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(RatBook), "only RatBook can call this function"); 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(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of ratscam if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = RatBook.getPlayerID(msg.sender); bytes32 _name = RatBook.getPlayerName(_pID); uint256 _laff = RatBook.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, RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(RSdatasets.EventReturns memory _eventData_) private returns (RSdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; // grab our pot amount // add airdrop pot into the final pot 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(45)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_)) / 100; // calculate ppt for round mask uint256 _ppt = 0; if(round_[_rID].keys > 0) { _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); } uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _com = _com.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards adminAddress.transfer(_com); // 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); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.newPot = 0; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = 0; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rID) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rID); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rID].mask = _earnings.add(plyrRnds_[_pID][_rID].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth * 5 / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now); } else { // no affiliates, add to community _com += _aff; } // pay out team adminAddress.transfer(_com); return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private returns(RSdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_)) / 100; // toss 5% into airdrop pot uint256 _air = (_eth / 20); airDropPot_ = airDropPot_.add(_air); // calculate pot (20%) uint256 _pot = (_eth.mul(20) / 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(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit RSEvents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only owner can activate require( msg.sender == adminAddress, "only owner can activate" ); // can only be ran once require(activated_ == false, "ratscam already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now - rndGap_; round_[1].end = now + rndInit_; } function setNextRndTime(uint32 rndInit, uint32 rndInc, uint32 rndMax) public { // only owner require(msg.sender == adminAddress, "only owner can setNextRndTime"); rndInit_ = rndInit * 1 hours; rndInc_ = rndInc * 1 seconds; rndMax_ = rndMax * 1 hours; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RSdatasets { //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 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 laff; // last affiliate id used uint256 lrnd; // last round played } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask } struct Round { uint256 plyr; // pID of player 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 } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RSKeysCalc { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //interface RatInterfaceForForwarder { // function deposit() external payable returns(bool); //} interface RatBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } }
gives square. multiplies x by x/
function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); }
429,803
/* * Just Price Protocol Smart Contract. * Copyright &#169; 2018 by ABDK Consulting. * Author: Mikhail Vladimirov <<span class="__cf_email__" data-cfemail="d3bebab8bbb2babffda5bfb2b7babebaa1bca593b4beb2babffdb0bcbe">[email&#160;protected]</span>> */ pragma solidity ^0.4.20; //import "./SafeMath.sol"; //import "./OrgonToken.sol"; //import "./OrisSpace.sol"; contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () public view returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) public view returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) public returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) public view returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } contract OrisSpace { /** * Start Oris Space smart contract. * * @param _returnAmount amount of tokens to return to message sender. */ function start (uint256 _returnAmount) public; } contract OrgonToken is Token { /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) public returns (bool); /** * Burn given number of tokens belonging to message sender. * May only be called by smart contract owner. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) public returns (bool); } /** * Just Price Protocol Smart Contract that serves as market maker for Orgon * tokens. */ contract JustPriceProtocol is SafeMath { /** * 2^128. */ uint256 internal constant TWO_128 = 0x100000000000000000000000000000000; /** * Sale start time (2018-04-19 06:00:00 UTC) */ uint256 internal constant SALE_START_TIME = 1524117600; /** * "Reserve" stage deadline (2018-07-08 00:00:00 UTC) */ uint256 internal constant RESERVE_DEADLINE = 1531008000; /** * Maximum amount to be collected during "reserve" stage. */ uint256 internal constant RESERVE_MAX_AMOUNT = 72500 ether; /** * Minimum amount to be collected during "reserve" stage. */ uint256 internal constant RESERVE_MIN_AMOUNT = 30000 ether; /** * Maximum number of tokens to be sold during "reserve" stage. */ uint256 internal constant RESERVE_MAX_TOKENS = 82881476.72e9; /** * ORNG/ETH ratio after "reserve" stage in Wei per ORGN unit. */ uint256 internal constant RESERVE_RATIO = 72500 ether / 725000000e9; /** * Maximum amount of ETH to collect at price 1. */ uint256 internal constant RESERVE_THRESHOLD_1 = 10000 ether; /** * Price 1 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_1 = 0.00080 ether / 1e9; /** * Maximum amount of ETH to collect at price 2. */ uint256 internal constant RESERVE_THRESHOLD_2 = 20000 ether; /** * Price 2 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_2 = 0.00082 ether / 1e9; /** * Maximum amount of ETH to collect at price 3. */ uint256 internal constant RESERVE_THRESHOLD_3 = 30000 ether; /** * Price 3 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_3 = 0.00085 ether / 1e9; /** * Maximum amount of ETH to collect at price 4. */ uint256 internal constant RESERVE_THRESHOLD_4 = 40000 ether; /** * Price 4 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_4 = 0.00088 ether / 1e9; /** * Maximum amount of ETH to collect at price 5. */ uint256 internal constant RESERVE_THRESHOLD_5 = 50000 ether; /** * Price 5 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_5 = 0.00090 ether / 1e9; /** * Maximum amount of ETH to collect at price 6. */ uint256 internal constant RESERVE_THRESHOLD_6 = 60000 ether; /** * Price 6 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_6 = 0.00092 ether / 1e9; /** * Maximum amount of ETH to collect at price 7. */ uint256 internal constant RESERVE_THRESHOLD_7 = 70000 ether; /** * Price 7 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_7 = 0.00095 ether / 1e9; /** * Maximum amount of ETH to collect at price 8. */ uint256 internal constant RESERVE_THRESHOLD_8 = 72500 ether; /** * Price 8 in Wei per ORGN unit. */ uint256 internal constant RESERVE_PRICE_8 = 0.00098 ether / 1e9; /** * "Growth" stage ends once this many tokens were issued. */ uint256 internal constant GROWTH_MAX_TOKENS = 1000000000e9; /** * Maximum duration of "growth" stage. */ uint256 internal constant GROWTH_MAX_DURATION = 285 days; /** * Numerator of fraction of tokens bought at "reserve" stage to be delivered * before "growth" stage start. */ uint256 internal constant GROWTH_MIN_DELIVERED_NUMERATOR = 75; /** * Denominator of fraction of tokens bought at "reserve" stage to be delivered * before "growth" stage start. */ uint256 internal constant GROWTH_MIN_DELIVERED_DENOMINATIOR = 100; /** * Numerator of fraction of total votes to be given to a new K1 address for * vote to succeed. */ uint256 internal constant REQUIRED_VOTES_NUMERATIOR = 51; /** * Denominator of fraction of total votes to be given to a new K1 address for * vote to succeed. */ uint256 internal constant REQUIRED_VOTES_DENOMINATOR = 100; /** * Fee denominator (1 / 20000 = 0.00005). */ uint256 internal constant FEE_DENOMINATOR = 20000; /** * Delay after start of "growth" stage before fee may be changed. */ uint256 internal constant FEE_CHANGE_DELAY = 650 days; /** * Minimum fee (1 / 20000 = 0.0005). */ uint256 internal constant MIN_FEE = 1; /** * Maximum fee (2000 / 20000 = 0.1). */ uint256 internal constant MAX_FEE = 2000; /** * Deploy Just Price Protocol smart contract with given Orgon Token, * Oris Space, and K1 wallet. * * @param _orgonToken Orgon Token to use * @param _orisSpace Oris Space to use * @param _k1 address of K1 wallet */ function JustPriceProtocol ( OrgonToken _orgonToken, OrisSpace _orisSpace, address _k1) public { orgonToken = _orgonToken; orisSpace = _orisSpace; k1 = _k1; } /** * When called with no data does the same as buyTokens (). */ function () public payable { require (msg.data.length == 0); buyTokens (); } /** * Buy tokens. */ function buyTokens () public payable { require (msg.value > 0); updateStage (); if (stage == Stage.RESERVE) buyTokensReserve (); else if (stage == Stage.GROWTH || stage == Stage.LIFE) buyTokensGrowthLife (); else revert (); // No buying in current stage } /** * Sell tokens. * * @param _value number of tokens to sell */ function sellTokens (uint256 _value) public { require (_value > 0); require (_value < TWO_128); updateStage (); require (stage == Stage.LIFE); assert (reserveAmount < TWO_128); uint256 totalSupply = orgonToken.totalSupply (); require (totalSupply < TWO_128); require (_value <= totalSupply); uint256 toPay = safeMul ( reserveAmount, safeSub ( TWO_128, pow_10 (safeSub (TWO_128, (_value << 128) / totalSupply)))) >> 128; require (orgonToken.transferFrom (msg.sender, this, _value)); require (orgonToken.burnTokens (_value)); reserveAmount = safeSub (reserveAmount, toPay); msg.sender.transfer (toPay); } /** * Deliver tokens sold during "reserve" stage to corresponding investors. * * @param _investors addresses of investors to deliver tokens to */ function deliver (address [] _investors) public { updateStage (); require ( stage == Stage.BEFORE_GROWTH || stage == Stage.GROWTH || stage == Stage.LIFE); for (uint256 i = 0; i < _investors.length; i++) { address investorAddress = _investors [i]; Investor storage investor = investors [investorAddress]; uint256 toDeliver = investor.tokensBought; investor.tokensBought = 0; investor.etherInvested = 0; if (toDeliver > 0) { require (orgonToken.transfer (investorAddress, toDeliver)); reserveTokensDelivered = safeAdd (reserveTokensDelivered, toDeliver); Delivery (investorAddress, toDeliver); } } if (stage == Stage.BEFORE_GROWTH && safeMul (reserveTokensDelivered, GROWTH_MIN_DELIVERED_DENOMINATIOR) >= safeMul (reserveTokensSold, GROWTH_MIN_DELIVERED_NUMERATOR)) { stage = Stage.GROWTH; growthDeadline = currentTime () + GROWTH_MAX_DURATION; feeChangeEnableTime = currentTime () + FEE_CHANGE_DELAY; } } /** * Refund investors who bought tokens during "reserve" stage. * * @param _investors addresses of investors to refund */ function refund (address [] _investors) public { updateStage (); require (stage == Stage.REFUND); for (uint256 i = 0; i < _investors.length; i++) { address investorAddress = _investors [i]; Investor storage investor = investors [investorAddress]; uint256 toBurn = investor.tokensBought; uint256 toRefund = investor.etherInvested; investor.tokensBought = 0; investor.etherInvested = 0; if (toBurn > 0) require (orgonToken.burnTokens (toBurn)); if (toRefund > 0) { investorAddress.transfer (toRefund); Refund (investorAddress, toRefund); } } } function vote (address _newK1) public { updateStage (); require (stage == Stage.LIFE); require (!k1Changed); uint256 votesCount = voteNumbers [msg.sender]; if (votesCount > 0) { address oldK1 = votes [msg.sender]; if (_newK1 != oldK1) { if (oldK1 != address (0)) { voteResults [oldK1] = safeSub (voteResults [oldK1], votesCount); VoteRevocation (msg.sender, oldK1, votesCount); } votes [msg.sender] = _newK1; if (_newK1 != address (0)) { voteResults [_newK1] = safeAdd (voteResults [_newK1], votesCount); Vote (msg.sender, _newK1, votesCount); if (safeMul (voteResults [_newK1], REQUIRED_VOTES_DENOMINATOR) >= safeMul (totalVotesNumber, REQUIRED_VOTES_NUMERATIOR)) { k1 = _newK1; k1Changed = true; K1Change (_newK1); } } } } } /** * Set new fee numerator. * * @param _fee new fee numerator. */ function setFee (uint256 _fee) public { require (msg.sender == k1); require (_fee >= MIN_FEE); require (_fee <= MAX_FEE); updateStage (); require (stage == Stage.GROWTH || stage == Stage.LIFE); require (currentTime () >= feeChangeEnableTime); require (safeSub (_fee, 1) <= fee); require (safeAdd (_fee, 1) >= fee); if (fee != _fee) { fee = _fee; FeeChange (_fee); } } /** * Get number of tokens bought by given investor during reserve stage that are * not yet delivered to him. * * @param _investor address of investor to get number of outstanding tokens * for * @return number of non-delivered tokens given investor bought during reserve * stage */ function outstandingTokens (address _investor) public view returns (uint256) { return investors [_investor].tokensBought; } /** * Get current stage of Just Price Protocol. * * @param _currentTime current time in seconds since epoch * @return current stage of Just Price Protocol */ function getStage (uint256 _currentTime) public view returns (Stage) { Stage currentStage = stage; if (currentStage == Stage.BEFORE_RESERVE) { if (_currentTime >= SALE_START_TIME) currentStage = Stage.RESERVE; else return currentStage; } if (currentStage == Stage.RESERVE) { if (_currentTime >= RESERVE_DEADLINE) { if (reserveAmount >= RESERVE_MIN_AMOUNT) currentStage = Stage.BEFORE_GROWTH; else currentStage = Stage.REFUND; } return currentStage; } if (currentStage == Stage.GROWTH) { if (_currentTime >= growthDeadline) { currentStage = Stage.LIFE; } } return currentStage; } /** * Return total number of votes eligible for choosing new K1 address. * * @return total number of votes eligible for choosing new K1 address */ function totalEligibleVotes () public view returns (uint256) { return totalVotesNumber; } /** * Return number of votes eligible for choosing new K1 address given investor * has. * * @param _investor address of investor to get number of eligible votes of * @return Number of eligible votes given investor has */ function eligibleVotes (address _investor) public view returns (uint256) { return voteNumbers [_investor]; } /** * Get number of votes for the given new K1 address. * * @param _newK1 new K1 address to get number of votes for * @return number of votes for the given new K1 address */ function votesFor (address _newK1) public view returns (uint256) { return voteResults [_newK1]; } /** * Buy tokens during "reserve" stage. */ function buyTokensReserve () internal { require (stage == Stage.RESERVE); uint256 toBuy = 0; uint256 toRefund = msg.value; uint256 etherInvested = 0; uint256 tokens; uint256 tokensValue; if (reserveAmount < RESERVE_THRESHOLD_1) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_1, reserveAmount)) / RESERVE_PRICE_1; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_1); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_2) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_2, reserveAmount)) / RESERVE_PRICE_2; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_2); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_3) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_3, reserveAmount)) / RESERVE_PRICE_3; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_3); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_4) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_4, reserveAmount)) / RESERVE_PRICE_4; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_4); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_5) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_5, reserveAmount)) / RESERVE_PRICE_5; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_5); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_6) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_6, reserveAmount)) / RESERVE_PRICE_6; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_6); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_7) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_7, reserveAmount)) / RESERVE_PRICE_7; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_7); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (reserveAmount < RESERVE_THRESHOLD_8) { tokens = min ( toRefund, safeSub (RESERVE_THRESHOLD_8, reserveAmount)) / RESERVE_PRICE_8; if (tokens > 0) { tokensValue = safeMul (tokens, RESERVE_PRICE_8); toBuy = safeAdd (toBuy, tokens); toRefund = safeSub (toRefund, tokensValue); etherInvested = safeAdd (etherInvested, tokensValue); reserveAmount = safeAdd (reserveAmount, tokensValue); } } if (toBuy > 0) { Investor storage investor = investors [msg.sender]; investor.tokensBought = safeAdd ( investor.tokensBought, toBuy); investor.etherInvested = safeAdd ( investor.etherInvested, etherInvested); reserveTokensSold = safeAdd (reserveTokensSold, toBuy); require (orgonToken.createTokens (toBuy)); voteNumbers [msg.sender] = safeAdd (voteNumbers [msg.sender], toBuy); totalVotesNumber = safeAdd (totalVotesNumber, toBuy); Investment (msg.sender, etherInvested, toBuy); if (safeSub (RESERVE_THRESHOLD_8, reserveAmount) < RESERVE_PRICE_8) { orisSpace.start (0); stage = Stage.BEFORE_GROWTH; } } if (toRefund > 0) msg.sender.transfer (toRefund); } /** * Buy tokens during "growth" or "life" stage. */ function buyTokensGrowthLife () internal { require (stage == Stage.GROWTH || stage == Stage.LIFE); require (msg.value < TWO_128); uint256 totalSupply = orgonToken.totalSupply (); assert (totalSupply < TWO_128); uint256 toBuy = safeMul ( totalSupply, safeSub ( root_10 (safeAdd (TWO_128, (msg.value << 128) / reserveAmount)), TWO_128)) >> 128; reserveAmount = safeAdd (reserveAmount, msg.value); require (reserveAmount < TWO_128); if (toBuy > 0) { require (orgonToken.createTokens (toBuy)); require (orgonToken.totalSupply () < TWO_128); uint256 feeAmount = safeMul (toBuy, fee) / FEE_DENOMINATOR; require (orgonToken.transfer (msg.sender, safeSub (toBuy, feeAmount))); if (feeAmount > 0) require (orgonToken.transfer (k1, feeAmount)); if (stage == Stage.GROWTH) { uint256 votesCount = toBuy; totalSupply = orgonToken.totalSupply (); if (totalSupply >= GROWTH_MAX_TOKENS) { stage = Stage.LIFE; votesCount = safeSub ( votesCount, safeSub (totalSupply, GROWTH_MAX_TOKENS)); } voteNumbers [msg.sender] = safeAdd (voteNumbers [msg.sender], votesCount); totalVotesNumber = safeAdd (totalVotesNumber, votesCount); } } } /** * Update stage of Just Price Protocol and return updated stage. * * @return updated stage of Just Price Protocol */ function updateStage () internal returns (Stage) { Stage currentStage = getStage (currentTime ()); if (stage != currentStage) { if (currentStage == Stage.BEFORE_GROWTH) { // "Reserve" stage deadline reached and minimum amount collected uint256 tokensToBurn = safeSub ( safeAdd ( safeAdd ( safeSub (RESERVE_MAX_AMOUNT, reserveAmount), safeSub (RESERVE_RATIO, 1)) / RESERVE_RATIO, reserveTokensSold), RESERVE_MAX_TOKENS); orisSpace.start (tokensToBurn); if (tokensToBurn > 0) require (orgonToken.burnTokens (tokensToBurn)); } stage = currentStage; } } /** * Get minimum of two values. * * @param x first value * @param y second value * @return minimum of two values */ function min (uint256 x, uint256 y) internal pure returns (uint256) { return x < y ? x : y; } /** * Calculate 2^128 * (x / 2^128)^(1/10). * * @param x parameter x * @return 2^128 * (x / 2^128)^(1/10) */ function root_10 (uint256 x) internal pure returns (uint256 y) { uint256 shift = 0; while (x > TWO_128) { x >>= 10; shift += 1; } if (x == TWO_128 || x == 0) y = x; else { uint256 x128 = x << 128; y = TWO_128; uint256 t = x; while (true) { t <<= 10; if (t < TWO_128) y >>= 1; else break; } for (uint256 i = 0; i < 16; i++) { uint256 y9; if (y == TWO_128) y9 = y; else { uint256 y2 = (y * y) >> 128; uint256 y4 = (y2 * y2) >> 128; uint256 y8 = (y4 * y4) >> 128; y9 = (y * y8) >> 128; } y = (9 * y + x128 / y9) / 10; assert (y <= TWO_128); } } y <<= shift; } /** * Calculate 2^128 * (x / 2^128)^10. * * @param x parameter x * @return 2^128 * (x / 2^128)^10 */ function pow_10 (uint256 x) internal pure returns (uint256) { require (x <= TWO_128); if (x == TWO_128) return x; else { uint256 x2 = (x * x) >> 128; uint256 x4 = (x2 * x2) >> 128; uint256 x8 = (x4 * x4) >> 128; return (x2 * x8) >> 128; } } /** * Get current time in seconds since epoch. * * @return current time in seconds since epoch */ function currentTime () internal view returns (uint256) { return block.timestamp; } /** * Just Price Protocol stages. * +----------------+ * | BEFORE_RESERVE | * +----------------+ * | * | Sale start time reached * V * +---------+ Reserve deadline reached * | RESERVE |-------------------------------+ * +---------+ | * | | * | 72500 ETH collected | * V | * +---------------+ 39013,174672 ETH collected | * | BEFORE_GROWTH |<---------------------------O * +---------------+ | * | | 39013,174672 ETH not collected * | 80% of tokens delivered | * V V * +------------+ +--------+ * | GROWTH | | REFUND | * +------------+ +--------+ * | * | 1,500,000,000 tokens issued or 365 days passed since start of "GROWTH" stage * V * +------+ * | LIFE | * +------+ */ enum Stage { BEFORE_RESERVE, // Before start of "Reserve" stage RESERVE, // "Reserve" stage BEFORE_GROWTH, // Between "Reserve" and "Growth" stages GROWTH, // "Grows" stage LIFE, // "Life" stage REFUND // "Refund" stage } /** * Orgon Token smart contract. */ OrgonToken internal orgonToken; /** * Oris Space spart contract. */ OrisSpace internal orisSpace; /** * Address of K1 smart contract. */ address internal k1; /** * Last known stage of Just Price Protocol */ Stage internal stage = Stage.BEFORE_RESERVE; /** * Amount of ether in reserve. */ uint256 internal reserveAmount; /** * Number of tokens sold during "reserve" stage. */ uint256 internal reserveTokensSold; /** * Number of tokens sold during "reserve" stage that were already delivered to * investors. */ uint256 internal reserveTokensDelivered; /** * "Growth" stage deadline. */ uint256 internal growthDeadline; /** * Mapping from address of a person who bought some tokens during "reserve" * stage to information about how many tokens he bought to how much ether * invested. */ mapping (address => Investor) internal investors; /** * Mapping from address of an investor to the number of votes this investor * has. */ mapping (address => uint256) internal voteNumbers; /** * Mapping from address of an investor to the new K1 address this investor * voted for. */ mapping (address => address) internal votes; /** * Mapping from suggested new K1 address to the number of votes for this * address. */ mapping (address => uint256) internal voteResults; /** * Total number of eligible votes. */ uint256 internal totalVotesNumber; /** * Whether K1 address was already changed via voting. */ bool internal k1Changed = false; /** * Fee enumerator. (2 / 20000 = 0.0001); */ uint256 internal fee = 2; /** * Time when fee changing is enabled. */ uint256 internal feeChangeEnableTime; /** * Encapsulates information about a person who bought some tokens during * "reserve" stage. */ struct Investor { /** * Number of tokens bought during reserve stage. */ uint256 tokensBought; /** * Ether invested during reserve stage. */ uint256 etherInvested; } /** * Logged when investor invested some ether during "reserve" stage. * * @param investor address of investor * @param value amount of ether invested * @param amount number of tokens issued for investor */ event Investment (address indexed investor, uint256 value, uint256 amount); /** * Logged when tokens bought at "reserve" stage were delivered to investor. * * @param investor address of investor whom tokens were delivered to * @param amount number of tokens delivered */ event Delivery (address indexed investor, uint256 amount); /** * Logged when investment was refunded. * * @param investor address of investor whose investment was refunded * @param value amount of ether refunded */ event Refund (address indexed investor, uint256 value); /** * Logged when K1 address was changed. * * @param k1 new K1 address */ event K1Change (address k1); /** * Logged when investor voted for new K1 address. * * @param investor investor who voted for new K1 address * @param newK1 new K1 address investor voted for * @param votes number of votes investor has */ event Vote (address indexed investor, address indexed newK1, uint256 votes); /** * Logged when investor revoked vote for new K1 address. * * @param investor investor who revoked vote for new K1 address * @param newK1 new K1 address investor revoked vote for * @param votes number of votes investor has */ event VoteRevocation ( address indexed investor, address indexed newK1, uint256 votes); /** * Logged when fee was changed. * * @param fee new fee numerator */ event FeeChange (uint256 fee); }
Set new fee numerator. _fee new fee numerator./
function setFee (uint256 _fee) public { require (msg.sender == k1); require (_fee >= MIN_FEE); require (_fee <= MAX_FEE); updateStage (); require (stage == Stage.GROWTH || stage == Stage.LIFE); require (currentTime () >= feeChangeEnableTime); require (safeSub (_fee, 1) <= fee); require (safeAdd (_fee, 1) >= fee); if (fee != _fee) { fee = _fee; FeeChange (_fee); } }
7,889,110
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // solhint-disable /** * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAL#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAL#" part is a known constant // (0x42414c23): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414c23000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Math uint256 internal constant ADD_OVERFLOW = 0; uint256 internal constant SUB_OVERFLOW = 1; uint256 internal constant SUB_UNDERFLOW = 2; uint256 internal constant MUL_OVERFLOW = 3; uint256 internal constant ZERO_DIVISION = 4; uint256 internal constant DIV_INTERNAL = 5; uint256 internal constant X_OUT_OF_BOUNDS = 6; uint256 internal constant Y_OUT_OF_BOUNDS = 7; uint256 internal constant PRODUCT_OUT_OF_BOUNDS = 8; uint256 internal constant INVALID_EXPONENT = 9; // Input uint256 internal constant OUT_OF_BOUNDS = 100; uint256 internal constant UNSORTED_ARRAY = 101; uint256 internal constant UNSORTED_TOKENS = 102; uint256 internal constant INPUT_LENGTH_MISMATCH = 103; uint256 internal constant ZERO_TOKEN = 104; // Shared pools uint256 internal constant MIN_TOKENS = 200; uint256 internal constant MAX_TOKENS = 201; uint256 internal constant MAX_SWAP_FEE_PERCENTAGE = 202; uint256 internal constant MIN_SWAP_FEE_PERCENTAGE = 203; uint256 internal constant MINIMUM_BPT = 204; uint256 internal constant CALLER_NOT_VAULT = 205; uint256 internal constant UNINITIALIZED = 206; uint256 internal constant BPT_IN_MAX_AMOUNT = 207; uint256 internal constant BPT_OUT_MIN_AMOUNT = 208; uint256 internal constant EXPIRED_PERMIT = 209; uint256 internal constant NOT_TWO_TOKENS = 210; // Pools uint256 internal constant MIN_AMP = 300; uint256 internal constant MAX_AMP = 301; uint256 internal constant MIN_WEIGHT = 302; uint256 internal constant MAX_STABLE_TOKENS = 303; uint256 internal constant MAX_IN_RATIO = 304; uint256 internal constant MAX_OUT_RATIO = 305; uint256 internal constant MIN_BPT_IN_FOR_TOKEN_OUT = 306; uint256 internal constant MAX_OUT_BPT_FOR_TOKEN_IN = 307; uint256 internal constant NORMALIZED_WEIGHT_INVARIANT = 308; uint256 internal constant INVALID_TOKEN = 309; uint256 internal constant UNHANDLED_JOIN_KIND = 310; uint256 internal constant ZERO_INVARIANT = 311; uint256 internal constant ORACLE_INVALID_SECONDS_QUERY = 312; uint256 internal constant ORACLE_NOT_INITIALIZED = 313; uint256 internal constant ORACLE_QUERY_TOO_OLD = 314; uint256 internal constant ORACLE_INVALID_INDEX = 315; uint256 internal constant ORACLE_BAD_SECS = 316; uint256 internal constant AMP_END_TIME_TOO_CLOSE = 317; uint256 internal constant AMP_ONGOING_UPDATE = 318; uint256 internal constant AMP_RATE_TOO_HIGH = 319; uint256 internal constant AMP_NO_ONGOING_UPDATE = 320; uint256 internal constant STABLE_INVARIANT_DIDNT_CONVERGE = 321; uint256 internal constant STABLE_GET_BALANCE_DIDNT_CONVERGE = 322; uint256 internal constant RELAYER_NOT_CONTRACT = 323; uint256 internal constant BASE_POOL_RELAYER_NOT_CALLED = 324; uint256 internal constant REBALANCING_RELAYER_REENTERED = 325; uint256 internal constant GRADUAL_UPDATE_TIME_TRAVEL = 326; uint256 internal constant SWAPS_DISABLED = 327; uint256 internal constant CALLER_IS_NOT_LBP_OWNER = 328; uint256 internal constant PRICE_RATE_OVERFLOW = 329; uint256 internal constant INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED = 330; uint256 internal constant WEIGHT_CHANGE_TOO_FAST = 331; uint256 internal constant LOWER_GREATER_THAN_UPPER_TARGET = 332; uint256 internal constant UPPER_TARGET_TOO_HIGH = 333; uint256 internal constant UNHANDLED_BY_LINEAR_POOL = 334; uint256 internal constant OUT_OF_TARGET_RANGE = 335; uint256 internal constant UNHANDLED_EXIT_KIND = 336; uint256 internal constant UNAUTHORIZED_EXIT = 337; uint256 internal constant MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 338; uint256 internal constant UNHANDLED_BY_MANAGED_POOL = 339; uint256 internal constant UNHANDLED_BY_PHANTOM_POOL = 340; uint256 internal constant TOKEN_DOES_NOT_HAVE_RATE_PROVIDER = 341; uint256 internal constant INVALID_INITIALIZATION = 342; uint256 internal constant OUT_OF_NEW_TARGET_RANGE = 343; uint256 internal constant UNAUTHORIZED_OPERATION = 344; uint256 internal constant UNINITIALIZED_POOL_CONTROLLER = 345; // Lib uint256 internal constant REENTRANCY = 400; uint256 internal constant SENDER_NOT_ALLOWED = 401; uint256 internal constant PAUSED = 402; uint256 internal constant PAUSE_WINDOW_EXPIRED = 403; uint256 internal constant MAX_PAUSE_WINDOW_DURATION = 404; uint256 internal constant MAX_BUFFER_PERIOD_DURATION = 405; uint256 internal constant INSUFFICIENT_BALANCE = 406; uint256 internal constant INSUFFICIENT_ALLOWANCE = 407; uint256 internal constant ERC20_TRANSFER_FROM_ZERO_ADDRESS = 408; uint256 internal constant ERC20_TRANSFER_TO_ZERO_ADDRESS = 409; uint256 internal constant ERC20_MINT_TO_ZERO_ADDRESS = 410; uint256 internal constant ERC20_BURN_FROM_ZERO_ADDRESS = 411; uint256 internal constant ERC20_APPROVE_FROM_ZERO_ADDRESS = 412; uint256 internal constant ERC20_APPROVE_TO_ZERO_ADDRESS = 413; uint256 internal constant ERC20_TRANSFER_EXCEEDS_ALLOWANCE = 414; uint256 internal constant ERC20_DECREASED_ALLOWANCE_BELOW_ZERO = 415; uint256 internal constant ERC20_TRANSFER_EXCEEDS_BALANCE = 416; uint256 internal constant ERC20_BURN_EXCEEDS_ALLOWANCE = 417; uint256 internal constant SAFE_ERC20_CALL_FAILED = 418; uint256 internal constant ADDRESS_INSUFFICIENT_BALANCE = 419; uint256 internal constant ADDRESS_CANNOT_SEND_VALUE = 420; uint256 internal constant SAFE_CAST_VALUE_CANT_FIT_INT256 = 421; uint256 internal constant GRANT_SENDER_NOT_ADMIN = 422; uint256 internal constant REVOKE_SENDER_NOT_ADMIN = 423; uint256 internal constant RENOUNCE_SENDER_NOT_ALLOWED = 424; uint256 internal constant BUFFER_PERIOD_EXPIRED = 425; uint256 internal constant CALLER_IS_NOT_OWNER = 426; uint256 internal constant NEW_OWNER_IS_ZERO = 427; uint256 internal constant CODE_DEPLOYMENT_FAILED = 428; uint256 internal constant CALL_TO_NON_CONTRACT = 429; uint256 internal constant LOW_LEVEL_CALL_FAILED = 430; uint256 internal constant NOT_PAUSED = 431; uint256 internal constant ADDRESS_ALREADY_ALLOWLISTED = 432; uint256 internal constant ADDRESS_NOT_ALLOWLISTED = 433; // Vault uint256 internal constant INVALID_POOL_ID = 500; uint256 internal constant CALLER_NOT_POOL = 501; uint256 internal constant SENDER_NOT_ASSET_MANAGER = 502; uint256 internal constant USER_DOESNT_ALLOW_RELAYER = 503; uint256 internal constant INVALID_SIGNATURE = 504; uint256 internal constant EXIT_BELOW_MIN = 505; uint256 internal constant JOIN_ABOVE_MAX = 506; uint256 internal constant SWAP_LIMIT = 507; uint256 internal constant SWAP_DEADLINE = 508; uint256 internal constant CANNOT_SWAP_SAME_TOKEN = 509; uint256 internal constant UNKNOWN_AMOUNT_IN_FIRST_SWAP = 510; uint256 internal constant MALCONSTRUCTED_MULTIHOP_SWAP = 511; uint256 internal constant INTERNAL_BALANCE_OVERFLOW = 512; uint256 internal constant INSUFFICIENT_INTERNAL_BALANCE = 513; uint256 internal constant INVALID_ETH_INTERNAL_BALANCE = 514; uint256 internal constant INVALID_POST_LOAN_BALANCE = 515; uint256 internal constant INSUFFICIENT_ETH = 516; uint256 internal constant UNALLOCATED_ETH = 517; uint256 internal constant ETH_TRANSFER = 518; uint256 internal constant CANNOT_USE_ETH_SENTINEL = 519; uint256 internal constant TOKENS_MISMATCH = 520; uint256 internal constant TOKEN_NOT_REGISTERED = 521; uint256 internal constant TOKEN_ALREADY_REGISTERED = 522; uint256 internal constant TOKENS_ALREADY_SET = 523; uint256 internal constant TOKENS_LENGTH_MUST_BE_2 = 524; uint256 internal constant NONZERO_TOKEN_BALANCE = 525; uint256 internal constant BALANCE_TOTAL_OVERFLOW = 526; uint256 internal constant POOL_NO_TOKENS = 527; uint256 internal constant INSUFFICIENT_FLASH_LOAN_BALANCE = 528; // Fees uint256 internal constant SWAP_FEE_PERCENTAGE_TOO_HIGH = 600; uint256 internal constant FLASH_LOAN_FEE_PERCENTAGE_TOO_HIGH = 601; uint256 internal constant INSUFFICIENT_FLASH_LOAN_FEE_AMOUNT = 602; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; import "../openzeppelin/IERC20.sol"; /** * @dev Interface for WETH9. * See https://github.com/gnosis/canonical-weth/blob/0dd1ea3e295eef916d0c6223ec63141137d22d67/contracts/WETH9.sol */ interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ISignaturesValidator.sol"; import "@balancer-labs/v2-solidity-utils/contracts/helpers/ITemporarilyPausable.sol"; import "@balancer-labs/v2-solidity-utils/contracts/misc/IWETH.sol"; import "./IAsset.sol"; import "./IAuthorizer.sol"; import "./IFlashLoanRecipient.sol"; import "./IProtocolFeesCollector.sol"; pragma solidity ^0.7.0; /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault is ISignaturesValidator, ITemporarilyPausable { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. /** * @dev Returns the Vault's Authorizer. */ function getAuthorizer() external view returns (IAuthorizer); /** * @dev Sets a new Authorizer for the Vault. The caller must be allowed by the current Authorizer to do this. * * Emits an `AuthorizerChanged` event. */ function setAuthorizer(IAuthorizer newAuthorizer) external; /** * @dev Emitted when a new authorizer is set by `setAuthorizer`. */ event AuthorizerChanged(IAuthorizer indexed newAuthorizer); // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged(address indexed relayer, address indexed sender, bool approved); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged(address indexed user, IERC20 indexed token, int256 delta); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer(IERC20 indexed token, address indexed sender, address recipient, uint256 amount); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered(bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered(bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Flash Loans /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoan( IFlashLoanRecipient recipient, IERC20[] memory tokens, uint256[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(IFlashLoanRecipient indexed recipient, IERC20 indexed token, uint256 amount, uint256 feeAmount); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); // Protocol Fees // // Some operations cause the Vault to collect tokens in the form of protocol fees, which can then be withdrawn by // permissioned accounts. // // There are two kinds of protocol fees: // // - flash loan fees: charged on all flash loans, as a percentage of the amounts lent. // // - swap fees: a percentage of the fees charged by Pools when performing swaps. For a number of reasons, including // swap gas costs and interface simplicity, protocol swap fees are not charged on each individual swap. Rather, // Pools are expected to keep track of how much they have charged in swap fees, and pay any outstanding debts to the // Vault when they are joined or exited. This prevents users from joining a Pool with unpaid debt, as well as // exiting a Pool in debt without first paying their share. /** * @dev Returns the current protocol fee module. */ function getProtocolFeesCollector() external view returns (IProtocolFeesCollector); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; /** * @dev Returns the Vault's WETH instance. */ function WETH() external view returns (IWETH); // solhint-disable-previous-line func-name-mixedcase } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev This is an empty interface used to represent either ERC20-conforming token contracts or ETH (using the zero * address sentinel value). We're just relying on the fact that `interface` can be used to declare new address-like * types. * * This concept is unrelated to a Pool's Asset Managers. */ interface IAsset { // solhint-disable-previous-line no-empty-blocks } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the SignatureValidator helper, used to support meta-transactions. */ interface ISignaturesValidator { /** * @dev Returns the EIP712 domain separator. */ function getDomainSeparator() external view returns (bytes32); /** * @dev Returns the next nonce used by an address to sign messages. */ function getNextNonce(address user) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; /** * @dev Interface for the TemporarilyPausable helper. */ interface ITemporarilyPausable { /** * @dev Emitted every time the pause state changes by `_setPaused`. */ event PausedStateChanged(bool paused); /** * @dev Returns the current paused state. */ function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; interface IAuthorizer { /** * @dev Returns true if `account` can perform the action described by `actionId` in the contract `where`. */ function canPerform( bytes32 actionId, address account, address where ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; // Inspired by Aave Protocol's IFlashLoanReceiver. import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory feeAmounts, bytes memory userData ) external; } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/IERC20.sol"; import "./IVault.sol"; import "./IAuthorizer.sol"; interface IProtocolFeesCollector { event SwapFeePercentageChanged(uint256 newSwapFeePercentage); event FlashLoanFeePercentageChanged(uint256 newFlashLoanFeePercentage); function withdrawCollectedFees( IERC20[] calldata tokens, uint256[] calldata amounts, address recipient ) external; function setSwapFeePercentage(uint256 newSwapFeePercentage) external; function setFlashLoanFeePercentage(uint256 newFlashLoanFeePercentage) external; function getSwapFeePercentage() external view returns (uint256); function getFlashLoanFeePercentage() external view returns (uint256); function getCollectedFeeAmounts(IERC20[] memory tokens) external view returns (uint256[] memory feeAmounts); function getAuthorizer() external view returns (IAuthorizer); function vault() external view returns (IVault); } // SPDX-License-Identifier: MIT // Based on the Address library from OpenZeppelin Contracts, altered by removing the `isContract` checks on // `functionCall` and `functionDelegateCall` in order to save gas, as the recipients are known to be contracts. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @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, Errors.ADDRESS_INSUFFICIENT_BALANCE); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); _require(success, Errors.ADDRESS_CANNOT_SEND_VALUE); } /** * @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: * * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.call(data); return verifyCallResult(success, returndata); } /** * @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) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata); } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling up the * revert reason or using the one provided. * * _Available since v4.3._ */ function verifyCallResult(bool success, bytes memory returndata) 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 // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { _revert(Errors.LOW_LEVEL_CALL_FAILED); } } } } // SPDX-License-Identifier: MIT // Based on the ReentrancyGuard library from OpenZeppelin Contracts, altered to reduce bytecode size. // Modifier code is inlined by the compiler, which causes its code to appear multiple times in the codebase. By using // private functions, we achieve the same end result with slightly higher runtime gas costs, but reduced bytecode size. pragma solidity ^0.7.0; import "../helpers/BalancerErrors.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _enterNonReentrant(); _; _exitNonReentrant(); } function _enterNonReentrant() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED _require(_status != _ENTERED, Errors.REENTRANCY); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _exitNonReentrant() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "@balancer-labs/v2-vault/contracts/interfaces/IVault.sol"; /** * @title IBalancerRelayer * @notice Allows safe multicall execution of a relayer's functions */ interface IBalancerRelayer { function getLibrary() external view returns (address); function getVault() external view returns (IVault); function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/Address.sol"; import "@balancer-labs/v2-solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "../interfaces/IBalancerRelayer.sol"; /** * @title Balancer Relayer * @notice Allows safe multicall execution of a relayer's functions * @dev * Relayers are formed out of a system of two contracts: * - This contract which acts as a single point of entry into the system through a multicall function * - A library contract which defines the allowed behaviour of the relayer * * The relayer entrypoint can then repeatedly delegatecall into the library's code to perform actions. * We can then run combinations of the library contract's functions in the context of the relayer entrypoint * without having to expose all these functions on the entrypoint contract itself. The multicall function is * then a single point of entry for all actions which can be easily protected against reentrancy. * * This design gives much stronger reentrancy guarantees as otherwise a malicious contract could reenter * the relayer through another function (which must allow reentrancy for multicall logic) which would * potentially allow them to manipulate global state resulting in loss of funds in some cases. * e.g. sweeping any leftover ETH which should have been refunded to the user. * * NOTE: Only the entrypoint contract should be whitelisted by Balancer governance as a relayer and so the Vault * will reject calls made if they are not being run from within the context of the entrypoint. * e.g. in the case where a user mistakenly calls into the library contract directly. */ contract BalancerRelayer is IBalancerRelayer, ReentrancyGuard { using Address for address payable; using Address for address; IVault private immutable _vault; address private immutable _library; /** * @dev This contract is not meant to be deployed directly by an EOA, but rather during construction of a child of * `BaseRelayerLibrary` which will provides its own address to be used as the relayer's library. */ constructor(IVault vault, address libraryAddress) { _vault = vault; _library = libraryAddress; } receive() external payable { // Accept ETH transfers only coming from the Vault. This is expected to happen due to a swap/exit/withdrawal // with ETH as an output should the relayer be listed as the recipient. This may also happen when // joining a pool, performing a swap or managing a user's balance does not use the full ETH value provided. // Any excess ETH value will be refunded back to this contract and forwarded back to the original sender. _require(msg.sender == address(_vault), Errors.ETH_TRANSFER); } function getVault() external view override returns (IVault) { return _vault; } function getLibrary() external view override returns (address) { return _library; } function multicall(bytes[] calldata data) external payable override nonReentrant returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { results[i] = _library.functionDelegateCall(data[i]); } _refundETH(); } function _refundETH() private { uint256 remainingEth = address(this).balance; if (remainingEth > 0) { msg.sender.sendValue(remainingEth); } } }
Returns the EIP712 domain separator./ Returns the next nonce used by an address to sign messages./ SPDX-License-Identifier: GPL-3.0-or-later This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http:www.gnu.org/licenses/>. Interface for the TemporarilyPausable helper./
interface ITemporarilyPausable { event PausedStateChanged(bool paused); function getPausedState() external view returns ( bool paused, uint256 pauseWindowEndTime, uint256 bufferPeriodEndTime ); }
140,654
./partial_match/1/0x4986d7BEe120DF657fcA29cc11BF0B04836118a2/sources/src/dependencies/openzeppelin/contracts/AccessControl.sol
Revert with a standard message if `account` is missing `role`. The format of the revert reason is given by the following regular expression: /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$//
function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(account), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } }
2,707,129
/** *Submitted for verification at Etherscan.io on 2021-03-12 */ pragma solidity 0.6.6; // File: @openzeppelin/contracts/GSN/Context.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 { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @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 /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/ERC20.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/oracle/LatestPriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface LatestPriceOracleInterface { /** * @dev Returns `true`if oracle is working. */ function isWorking() external returns (bool); /** * @dev Returns the last updated price. Decimals is 8. **/ function latestPrice() external returns (uint256); /** * @dev Returns the timestamp of the last updated price. */ function latestTimestamp() external returns (uint256); } // File: contracts/oracle/PriceOracleInterface.sol pragma solidity 0.6.6; /** * @dev Interface of the price oracle. */ interface PriceOracleInterface is LatestPriceOracleInterface { /** * @dev Returns the latest id. The id start from 1 and increments by 1. */ function latestId() external returns (uint256); /** * @dev Returns the historical price specified by `id`. Decimals is 8. */ function getPrice(uint256 id) external returns (uint256); /** * @dev Returns the timestamp of historical price specified by `id`. */ function getTimestamp(uint256 id) external returns (uint256); } // File: contracts/oracle/OracleInterface.sol pragma solidity 0.6.6; // Oracle referenced by OracleProxy must implement this interface. interface OracleInterface is PriceOracleInterface { function getVolatility() external returns (uint256); function lastCalculatedVolatility() external view returns (uint256); } // File: contracts/oracle/VolatilityOracleInterface.sol pragma solidity 0.6.6; interface VolatilityOracleInterface { function getVolatility(uint64 untilMaturity) external view returns (uint64 volatilityE8); } // File: contracts/util/TransferETHInterface.sol pragma solidity 0.6.6; interface TransferETHInterface { receive() external payable; event LogTransferETH(address indexed from, address indexed to, uint256 value); } // File: contracts/bondToken/BondTokenInterface.sol pragma solidity 0.6.6; interface BondTokenInterface is IERC20 { event LogExpire(uint128 rateNumerator, uint128 rateDenominator, bool firstTime); function mint(address account, uint256 amount) external returns (bool success); function expire(uint128 rateNumerator, uint128 rateDenominator) external returns (bool firstTime); function simpleBurn(address account, uint256 amount) external returns (bool success); function burn(uint256 amount) external returns (bool success); function burnAll() external returns (uint256 amount); function getRate() external view returns (uint128 rateNumerator, uint128 rateDenominator); } // File: contracts/bondMaker/BondMakerInterface.sol pragma solidity 0.6.6; interface BondMakerInterface { event LogNewBond( bytes32 indexed bondID, address indexed bondTokenAddress, uint256 indexed maturity, bytes32 fnMapID ); event LogNewBondGroup( uint256 indexed bondGroupID, uint256 indexed maturity, uint64 indexed sbtStrikePrice, bytes32[] bondIDs ); event LogIssueNewBonds( uint256 indexed bondGroupID, address indexed issuer, uint256 amount ); event LogReverseBondGroupToCollateral( uint256 indexed bondGroupID, address indexed owner, uint256 amount ); event LogExchangeEquivalentBonds( address indexed owner, uint256 indexed inputBondGroupID, uint256 indexed outputBondGroupID, uint256 amount ); event LogLiquidateBond( bytes32 indexed bondID, uint128 rateNumerator, uint128 rateDenominator ); function registerNewBond(uint256 maturity, bytes calldata fnMap) external returns ( bytes32 bondID, address bondTokenAddress, bytes32 fnMapID ); function registerNewBondGroup( bytes32[] calldata bondIDList, uint256 maturity ) external returns (uint256 bondGroupID); function reverseBondGroupToCollateral(uint256 bondGroupID, uint256 amount) external returns (bool success); function exchangeEquivalentBonds( uint256 inputBondGroupID, uint256 outputBondGroupID, uint256 amount, bytes32[] calldata exceptionBonds ) external returns (bool); function liquidateBond(uint256 bondGroupID, uint256 oracleHintID) external returns (uint256 totalPayment); function collateralAddress() external view returns (address); function oracleAddress() external view returns (PriceOracleInterface); function feeTaker() external view returns (address); function decimalsOfBond() external view returns (uint8); function decimalsOfOraclePrice() external view returns (uint8); function maturityScale() external view returns (uint256); function nextBondGroupID() external view returns (uint256); function getBond(bytes32 bondID) external view returns ( address bondAddress, uint256 maturity, uint64 solidStrikePrice, bytes32 fnMapID ); function getFnMap(bytes32 fnMapID) external view returns (bytes memory fnMap); function getBondGroup(uint256 bondGroupID) external view returns (bytes32[] memory bondIDs, uint256 maturity); function generateFnMapID(bytes calldata fnMap) external view returns (bytes32 fnMapID); function generateBondID(uint256 maturity, bytes calldata fnMap) external view returns (bytes32 bondID); } // File: contracts/bondPricer/Enums.sol pragma solidity 0.6.6; /** Pure SBT: ___________ / / / / LBT Shape: / / / / ______/ SBT Shape: ______ / / _______/ Triangle: /\ / \ / \ _______/ \________ */ enum BondType {NONE, PURE_SBT, SBT_SHAPE, LBT_SHAPE, TRIANGLE} // File: contracts/bondPricer/BondPricerInterface.sol pragma solidity 0.6.6; interface BondPricerInterface { /** * @notice Calculate bond price and leverage by black-scholes formula. * @param bondType type of target bond. * @param points coodinates of polyline which is needed for price calculation * @param spotPrice is a oracle price. * @param volatilityE8 is a oracle volatility. * @param untilMaturity Remaining period of target bond in second **/ function calcPriceAndLeverage( BondType bondType, uint256[] calldata points, int256 spotPrice, int256 volatilityE8, int256 untilMaturity ) external view returns (uint256 price, uint256 leverageE8); } // File: @openzeppelin/contracts/math/SignedSafeMath.sol /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File: @openzeppelin/contracts/utils/SafeCast.sol /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // File: contracts/math/UseSafeMath.sol pragma solidity 0.6.6; /** * @notice ((a - 1) / b) + 1 = (a + b -1) / b * for example a.add(10**18 -1).div(10**18) = a.sub(1).div(10**18) + 1 */ library SafeMathDivRoundUp { using SafeMath for uint256; function divRoundUp( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { if (a == 0) { return 0; } require(b > 0, errorMessage); return ((a - 1) / b) + 1; } function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return divRoundUp(a, b, "SafeMathDivRoundUp: modulo by zero"); } } /** * @title UseSafeMath * @dev One can use SafeMath for not only uint256 but also uin64 or uint16, * and also can use SafeCast for uint256. * For example: * uint64 a = 1; * uint64 b = 2; * a = a.add(b).toUint64() // `a` become 3 as uint64 * In addition, one can use SignedSafeMath and SafeCast.toUint256(int256) for int256. * In the case of the operation to the uint64 value, one needs to cast the value into int256 in * advance to use `sub` as SignedSafeMath.sub not SafeMath.sub. * For example: * int256 a = 1; * uint64 b = 2; * int256 c = 3; * a = a.add(int256(b).sub(c)); // `a` becomes 0 as int256 * b = a.toUint256().toUint64(); // `b` becomes 0 as uint64 */ abstract contract UseSafeMath { using SafeMath for uint256; using SafeMathDivRoundUp for uint256; using SafeMath for uint64; using SafeMathDivRoundUp for uint64; using SafeMath for uint16; using SignedSafeMath for int256; using SafeCast for uint256; using SafeCast for int256; } // File: contracts/util/Polyline.sol pragma solidity 0.6.6; contract Polyline is UseSafeMath { struct Point { uint64 x; // Value of the x-axis of the x-y plane uint64 y; // Value of the y-axis of the x-y plane } struct LineSegment { Point left; // The left end of the line definition range Point right; // The right end of the line definition range } /** * @notice Return the value of y corresponding to x on the given line. line in the form of * a rational number (numerator / denominator). * If you treat a line as a line segment instead of a line, you should run * includesDomain(line, x) to check whether x is included in the line's domain or not. * @dev To guarantee accuracy, the bit length of the denominator must be greater than or equal * to the bit length of x, and the bit length of the numerator must be greater than or equal * to the sum of the bit lengths of x and y. */ function _mapXtoY(LineSegment memory line, uint64 x) internal pure returns (uint128 numerator, uint64 denominator) { int256 x1 = int256(line.left.x); int256 y1 = int256(line.left.y); int256 x2 = int256(line.right.x); int256 y2 = int256(line.right.y); require(x2 > x1, "must be left.x < right.x"); denominator = uint64(x2 - x1); // Calculate y = ((x2 - x) * y1 + (x - x1) * y2) / (x2 - x1) // in the form of a fraction (numerator / denominator). int256 n = (x - x1) * y2 + (x2 - x) * y1; require(n >= 0, "underflow n"); require(n < 2**128, "system error: overflow n"); numerator = uint128(n); } /** * @notice Checking that a line segment is a valid format. */ function assertLineSegment(LineSegment memory segment) internal pure { uint64 x1 = segment.left.x; uint64 x2 = segment.right.x; require(x1 < x2, "must be left.x < right.x"); } /** * @notice Checking that a polyline is a valid format. */ function assertPolyline(LineSegment[] memory polyline) internal pure { uint256 numOfSegment = polyline.length; require(numOfSegment != 0, "polyline must not be empty array"); LineSegment memory leftSegment = polyline[0]; // mutable int256 gradientNumerator = int256(leftSegment.right.y) - int256(leftSegment.left.y); // mutable int256 gradientDenominator = int256(leftSegment.right.x) - int256(leftSegment.left.x); // mutable // The beginning of the first line segment's domain is 0. require( leftSegment.left.x == uint64(0), "the x coordinate of left end of the first segment must be 0" ); // The value of y when x is 0 is 0. require( leftSegment.left.y == uint64(0), "the y coordinate of left end of the first segment must be 0" ); // Making sure that the first line segment is a correct format. assertLineSegment(leftSegment); // The end of the domain of a segment and the beginning of the domain of the adjacent // segment must coincide. LineSegment memory rightSegment; // mutable for (uint256 i = 1; i < numOfSegment; i++) { rightSegment = polyline[i]; // Make sure that the i-th line segment is a correct format. assertLineSegment(rightSegment); // Checking that the x-coordinates are same. require( leftSegment.right.x == rightSegment.left.x, "given polyline has an undefined domain." ); // Checking that the y-coordinates are same. require( leftSegment.right.y == rightSegment.left.y, "given polyline is not a continuous function" ); int256 nextGradientNumerator = int256(rightSegment.right.y) - int256(rightSegment.left.y); int256 nextGradientDenominator = int256(rightSegment.right.x) - int256(rightSegment.left.x); require( nextGradientNumerator * gradientDenominator != nextGradientDenominator * gradientNumerator, "the sequential segments must not have the same gradient" ); leftSegment = rightSegment; gradientNumerator = nextGradientNumerator; gradientDenominator = nextGradientDenominator; } // rightSegment is lastSegment // About the last line segment. require( gradientNumerator >= 0 && gradientNumerator <= gradientDenominator, "the gradient of last line segment must be non-negative, and equal to or less than 1" ); } /** * @notice zip a LineSegment structure to uint256 * @return zip uint256( 0 ... 0 | x1 | y1 | x2 | y2 ) */ function zipLineSegment(LineSegment memory segment) internal pure returns (uint256 zip) { uint256 x1U256 = uint256(segment.left.x) << (64 + 64 + 64); // uint64 uint256 y1U256 = uint256(segment.left.y) << (64 + 64); // uint64 uint256 x2U256 = uint256(segment.right.x) << 64; // uint64 uint256 y2U256 = uint256(segment.right.y); // uint64 zip = x1U256 | y1U256 | x2U256 | y2U256; } /** * @notice unzip uint256 to a LineSegment structure */ function unzipLineSegment(uint256 zip) internal pure returns (LineSegment memory) { uint64 x1 = uint64(zip >> (64 + 64 + 64)); uint64 y1 = uint64(zip >> (64 + 64)); uint64 x2 = uint64(zip >> 64); uint64 y2 = uint64(zip); return LineSegment({ left: Point({x: x1, y: y1}), right: Point({x: x2, y: y2}) }); } /** * @notice unzip the fnMap to uint256[]. */ function decodePolyline(bytes memory fnMap) internal pure returns (uint256[] memory) { return abi.decode(fnMap, (uint256[])); } } // File: contracts/bondPricer/DetectBondShape.sol pragma solidity 0.6.6; contract DetectBondShape is Polyline { /** * @notice Detect bond type by polyline of bond. * @param bondID bondID of target bond token * @param submittedType if this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success whether bond detection succeeded or notice * @param points coodinates of polyline which is needed for price calculation **/ function getBondTypeByID( BondMakerInterface bondMaker, bytes32 bondID, BondType submittedType ) public view returns ( bool success, BondType, uint256[] memory points ) { (, , , bytes32 fnMapID) = bondMaker.getBond(bondID); bytes memory fnMap = bondMaker.getFnMap(fnMapID); return _getBondType(fnMap, submittedType); } /** * @notice Detect bond type by polyline of bond. * @param fnMap Function mapping of target bond token * @param submittedType If this parameter is BondType.NONE, this function checks up all bond types. Otherwise this function checks up only one bond type. * @param success Whether bond detection succeeded or not * @param points Coodinates of polyline which are needed for price calculation **/ function getBondType(bytes calldata fnMap, BondType submittedType) external pure returns ( bool success, BondType, uint256[] memory points ) { uint256[] memory polyline = decodePolyline(fnMap); LineSegment[] memory segments = new LineSegment[](polyline.length); for (uint256 i = 0; i < polyline.length; i++) { segments[i] = unzipLineSegment(polyline[i]); } assertPolyline(segments); return _getBondType(fnMap, submittedType); } function _getBondType(bytes memory fnMap, BondType submittedType) internal pure returns ( bool success, BondType, uint256[] memory points ) { if (submittedType == BondType.NONE) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } return (false, BondType.NONE, points); } else if (submittedType == BondType.PURE_SBT) { (success, points) = _isSBT(fnMap); if (success) { return (success, BondType.PURE_SBT, points); } } else if (submittedType == BondType.SBT_SHAPE) { (success, points) = _isSBTShape(fnMap); if (success) { return (success, BondType.SBT_SHAPE, points); } } else if (submittedType == BondType.LBT_SHAPE) { (success, points) = _isLBTShape(fnMap); if (success) { return (success, BondType.LBT_SHAPE, points); } } else if (submittedType == BondType.TRIANGLE) { (success, points) = _isTriangle(fnMap); if (success) { return (success, BondType.TRIANGLE, points); } } return (false, BondType.NONE, points); } function _isLBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isTriangle(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 4) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); LineSegment memory forthLine = unzipLineSegment(zippedLines[3]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == 0 && forthLine.right.x > thirdLine.right.x && forthLine.right.y == 0 ) { uint256[] memory _lines = new uint256[](4); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; _lines[3] = thirdLine.right.x; return (true, _lines); } return (false, points); } function _isSBTShape(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 3) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); LineSegment memory thirdLine = unzipLineSegment(zippedLines[2]); if ( secondLine.left.x != 0 && secondLine.left.y == 0 && secondLine.right.x > secondLine.left.x && secondLine.right.y != 0 && thirdLine.right.x > secondLine.right.x && thirdLine.right.y == secondLine.right.y ) { uint256[] memory _lines = new uint256[](3); _lines[0] = secondLine.left.x; _lines[1] = secondLine.right.x; _lines[2] = secondLine.right.y; return (true, _lines); } return (false, points); } function _isSBT(bytes memory fnMap) internal pure returns (bool isOk, uint256[] memory points) { uint256[] memory zippedLines = decodePolyline(fnMap); if (zippedLines.length != 2) { return (false, points); } LineSegment memory secondLine = unzipLineSegment(zippedLines[1]); if ( secondLine.left.x != 0 && secondLine.left.y == secondLine.left.x && secondLine.right.x > secondLine.left.x && secondLine.right.y == secondLine.left.y ) { uint256[] memory _lines = new uint256[](1); _lines[0] = secondLine.left.x; return (true, _lines); } return (false, points); } } // File: contracts/util/Time.sol pragma solidity 0.6.6; abstract contract Time { function _getBlockTimestampSec() internal view returns (uint256 unixtimesec) { unixtimesec = block.timestamp; // solhint-disable-line not-rely-on-time } } // File: contracts/generalizedDotc/BondExchange.sol pragma solidity 0.6.6; abstract contract BondExchange is UseSafeMath, Time { uint256 internal constant MIN_EXCHANGE_RATE_E8 = 0.000001 * 10**8; uint256 internal constant MAX_EXCHANGE_RATE_E8 = 1000000 * 10**8; int256 internal constant MAX_SPREAD_E8 = 10**8; // 100% /** * @dev the sum of decimalsOfBond of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND = 8; /** * @dev the sum of decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_ORACLE_PRICE = 8; BondMakerInterface internal immutable _bondMakerContract; PriceOracleInterface internal immutable _priceOracleContract; VolatilityOracleInterface internal immutable _volatilityOracleContract; LatestPriceOracleInterface internal immutable _volumeCalculator; DetectBondShape internal immutable _bondShapeDetector; /** * @param bondMakerAddress is a bond maker contract. * @param volumeCalculatorAddress is a contract to convert the unit of a strike price to USD. */ constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public { _assertBondMakerDecimals(bondMakerAddress); _bondMakerContract = bondMakerAddress; _priceOracleContract = bondMakerAddress.oracleAddress(); _volatilityOracleContract = VolatilityOracleInterface( volatilityOracleAddress ); _volumeCalculator = volumeCalculatorAddress; _bondShapeDetector = bondShapeDetector; } function bondMakerAddress() external view returns (BondMakerInterface) { return _bondMakerContract; } function volumeCalculatorAddress() external view returns (LatestPriceOracleInterface) { return _volumeCalculator; } /** * @dev Get the latest price (USD) and historical volatility using oracle. * If the oracle is not working, `latestPrice` reverts. * @return priceE8 (10^-8 USD) */ function _getLatestPrice(LatestPriceOracleInterface oracle) internal returns (uint256 priceE8) { return oracle.latestPrice(); } /** * @dev Get the implied volatility using oracle. * @return volatilityE8 (10^-8) */ function _getVolatility( VolatilityOracleInterface oracle, uint64 untilMaturity ) internal view returns (uint256 volatilityE8) { return oracle.getVolatility(untilMaturity); } /** * @dev Returns bond tokenaddress, maturity, */ function _getBond(BondMakerInterface bondMaker, bytes32 bondID) internal view returns ( ERC20 bondToken, uint256 maturity, uint256 sbtStrikePrice, bytes32 fnMapID ) { address bondTokenAddress; (bondTokenAddress, maturity, sbtStrikePrice, fnMapID) = bondMaker .getBond(bondID); // Revert if `bondTokenAddress` is zero. bondToken = ERC20(bondTokenAddress); } /** * @dev Removes a decimal gap from the first argument. */ function _applyDecimalGap( uint256 baseAmount, uint8 decimalsOfBase, uint8 decimalsOfQuote ) internal pure returns (uint256 quoteAmount) { uint256 n; uint256 d; if (decimalsOfBase > decimalsOfQuote) { d = decimalsOfBase - decimalsOfQuote; } else if (decimalsOfBase < decimalsOfQuote) { n = decimalsOfQuote - decimalsOfBase; } // The consequent multiplication would overflow under extreme and non-blocking circumstances. require(n < 19 && d < 19, "decimal gap needs to be lower than 19"); return baseAmount.mul(10**n).div(10**d); } function _calcBondPriceAndSpread( BondPricerInterface bondPricer, bytes32 bondID, int16 feeBaseE4 ) internal returns (uint256 bondPriceE8, int256 spreadE8) { (, uint256 maturity, , ) = _getBond(_bondMakerContract, bondID); ( bool isKnownBondType, BondType bondType, uint256[] memory points ) = _bondShapeDetector.getBondTypeByID( _bondMakerContract, bondID, BondType.NONE ); require(isKnownBondType, "cannot calculate the price of this bond"); uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); uint256 oraclePriceE8 = _getLatestPrice(_priceOracleContract); uint256 oracleVolatilityE8 = _getVolatility( _volatilityOracleContract, untilMaturity.toUint64() ); uint256 leverageE8; (bondPriceE8, leverageE8) = bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity.toInt256() ); spreadE8 = _calcSpread(oracleVolatilityE8, leverageE8, feeBaseE4); } function _calcSpread( uint256 oracleVolatilityE8, uint256 leverageE8, int16 feeBaseE4 ) internal pure returns (int256 spreadE8) { uint256 volE8 = oracleVolatilityE8 < 10**8 ? 10**8 : oracleVolatilityE8 > 2 * 10**8 ? 2 * 10**8 : oracleVolatilityE8; uint256 volTimesLevE16 = volE8 * leverageE8; // assert(volTimesLevE16 < 200 * 10**16); spreadE8 = (feeBaseE4 * ( feeBaseE4 < 0 || volTimesLevE16 < 10**16 ? 10**16 : volTimesLevE16 ) .toInt256()) / 10**12; spreadE8 = spreadE8 > MAX_SPREAD_E8 ? MAX_SPREAD_E8 : spreadE8; } /** * @dev Calculate the exchange volume on the USD basis. */ function _calcUsdPrice(uint256 amount) internal returns (uint256) { return amount.mul(_getLatestPrice(_volumeCalculator)) / 10**8; } /** * @dev Restirct the bond maker. */ function _assertBondMakerDecimals(BondMakerInterface bondMaker) internal view { require( bondMaker.decimalsOfOraclePrice() == DECIMALS_OF_ORACLE_PRICE, "the decimals of oracle price must be 8" ); require( bondMaker.decimalsOfBond() == DECIMALS_OF_BOND, "the decimals of bond token must be 8" ); } function _assertExpectedPriceRange( uint256 actualAmount, uint256 expectedAmount, uint256 range ) internal pure { if (expectedAmount != 0) { require( actualAmount.mul(1000 + range).div(1000) >= expectedAmount, "out of expected price range" ); } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.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"); } } } // File: contracts/generalizedDotc/BondVsErc20Exchange.sol pragma solidity 0.6.6; abstract contract BondVsErc20Exchange is BondExchange { using SafeERC20 for ERC20; struct VsErc20Pool { address seller; ERC20 swapPairToken; LatestPriceOracleInterface swapPairOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsErc20Pool) internal _vsErc20Pool; event LogCreateErc20ToBondPool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogCreateBondToErc20Pool( bytes32 indexed poolID, address indexed seller, address indexed swapPairAddress ); event LogUpdateVsErc20Pool( bytes32 indexed poolID, address swapPairOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsErc20Pool(bytes32 indexed poolID); event LogExchangeErc20ToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); event LogExchangeBondToErc20( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: ERC20.decimals() uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsErc20Pool(bytes32 poolID) { require( _vsErc20Pool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ERC20 token to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you approve ERC20 token to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeErc20ToBond( bytes32 bondID, bytes32 poolID, uint256 swapPairAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeErc20ToBond( msg.sender, bondID, poolID, swapPairAmount ); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ERC20 token. * @dev Ensure the seller has approved sufficient ERC20 token and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the exchange pair token amount to receive. * @param range (decimal: 3) */ function exchangeBondToErc20( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 swapPairAmount) { swapPairAmount = _exchangeBondToErc20( msg.sender, bondID, poolID, bondAmount ); // assert(swapPairAmount != 0); _assertExpectedPriceRange(swapPairAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToErc20(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToErc20(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) external view returns (bytes32 poolID) { return _generateVsErc20PoolID(seller, swapPairAddress, isBondSale); } /** * @notice Register a new vsErc20Pool. */ function createVsErc20Pool( ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsErc20Pool( msg.sender, swapPairAddress, swapPairOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsErc20Pool( poolID, swapPairOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsErc20Pool(bytes32 poolID) external { require( _vsErc20Pool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsErc20Pool(poolID); } /** * @notice Returns the pool settings. */ function getVsErc20Pool(bytes32 poolID) external view returns ( address seller, ERC20 swapPairAddress, LatestPriceOracleInterface swapPairOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsErc20Pool(poolID); } /** * @dev Exchange buyer's ERC20 token to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer approve ERC20 token to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeErc20ToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { ( uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToErc20(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); bondAmount = _applyDecimalGap( swapPairAmount, decimalsOfSwapPair, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(decimalsOfSwapPair) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(buyer, seller, swapPairAmount); emit LogExchangeErc20ToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ERC20 token. * Ensure the seller has approved sufficient ERC20 token and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received swap pair token amount. */ function _exchangeBondToErc20( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToErc20( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); uint8 decimalsOfSwapPair = swapPairToken.decimals(); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, decimalsOfSwapPair ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); swapPairToken.safeTransferFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToErc20( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToErc20(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , LatestPriceOracleInterface erc20Oracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsErc20Pool(poolID); swapPairPriceE8 = _getLatestPrice(erc20Oracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(10**8) / uint256(10**8 + spreadE8); } } function _generateVsErc20PoolID( address seller, address swapPairAddress, bool isBondSale ) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ERC20 exchange", address(this), seller, swapPairAddress, isBondSale ) ); } function _setVsErc20Pool( bytes32 poolID, address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(swapPairToken) != address(0), "swapPairToken should be non-zero address" ); require( address(swapPairOracle) != address(0), "swapPairOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsErc20Pool[poolID] = VsErc20Pool({ seller: seller, swapPairToken: swapPairToken, swapPairOracle: swapPairOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsErc20Pool( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsErc20PoolID( seller, address(swapPairToken), isBondSale ); require( _vsErc20Pool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = _getLatestPrice(swapPairOracle); require( price != 0, "swapPairOracle has latestPrice() function which returns non-zero value" ); } _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateErc20ToBondPool( poolID, seller, address(swapPairToken) ); } else { emit LogCreateBondToErc20Pool( poolID, seller, address(swapPairToken) ); } emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _updateVsErc20Pool( bytes32 poolID, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsErc20Pool(poolID) { ( address seller, ERC20 swapPairToken, , , , bool isBondSale ) = _getVsErc20Pool(poolID); _setVsErc20Pool( poolID, seller, swapPairToken, swapPairOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsErc20Pool( poolID, address(swapPairOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsErc20Pool(bytes32 poolID) internal isExsistentVsErc20Pool(poolID) { delete _vsErc20Pool[poolID]; emit LogDeleteVsErc20Pool(poolID); } function _getVsErc20Pool(bytes32 poolID) internal view isExsistentVsErc20Pool(poolID) returns ( address seller, ERC20 swapPairToken, LatestPriceOracleInterface swapPairOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsErc20Pool memory exchangePair = _vsErc20Pool[poolID]; seller = exchangePair.seller; swapPairToken = exchangePair.swapPairToken; swapPairOracle = exchangePair.swapPairOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } } // File: contracts/util/TransferETH.sol pragma solidity 0.6.6; abstract contract TransferETH is TransferETHInterface { receive() external payable override { emit LogTransferETH(msg.sender, address(this), msg.value); } function _hasSufficientBalance(uint256 amount) internal view returns (bool ok) { address thisContract = address(this); return amount <= thisContract.balance; } /** * @notice transfer `amount` ETH to the `recipient` account with emitting log */ function _transferETH( address payable recipient, uint256 amount, string memory errorMessage ) internal { require(_hasSufficientBalance(amount), errorMessage); (bool success, ) = recipient.call{value: amount}(""); // solhint-disable-line avoid-low-level-calls require(success, "transferring Ether failed"); emit LogTransferETH(address(this), recipient, amount); } function _transferETH(address payable recipient, uint256 amount) internal { _transferETH(recipient, amount, "TransferETH: transfer amount exceeds balance"); } } // File: contracts/generalizedDotc/BondVsEthExchange.sol pragma solidity 0.6.6; abstract contract BondVsEthExchange is BondExchange, TransferETH { uint8 internal constant DECIMALS_OF_ETH = 18; struct VsEthPool { address seller; LatestPriceOracleInterface ethOracle; BondPricerInterface bondPricer; int16 feeBaseE4; bool isBondSale; } mapping(bytes32 => VsEthPool) internal _vsEthPool; mapping(address => uint256) internal _depositedEth; event LogCreateEthToBondPool( bytes32 indexed poolID, address indexed seller ); event LogCreateBondToEthPool( bytes32 indexed poolID, address indexed seller ); event LogUpdateVsEthPool( bytes32 indexed poolID, address ethOracleAddress, address bondPricerAddress, int16 feeBase // decimal: 4 ); event LogDeleteVsEthPool(bytes32 indexed poolID); event LogExchangeEthToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); event LogExchangeBondToEth( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // decimal: 18 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsEthPool(bytes32 poolID) { require( _vsEthPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange buyer's ETH to the seller's bond. * @dev Ensure the seller has approved sufficient bonds and * you deposit ETH to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param ethAmount is the exchange pair token amount to pay. * @param expectedAmount is the bond amount to receive. * @param range (decimal: 3) */ function exchangeEthToBond( bytes32 bondID, bytes32 poolID, uint256 ethAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { bondAmount = _exchangeEthToBond(msg.sender, bondID, poolID, ethAmount); // assert(bondAmount != 0); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Exchange buyer's bond to the seller's ETH. * @dev Ensure the seller has deposited sufficient ETH and * you approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @param expectedAmount is the ETH amount to receive. * @param range (decimal: 3) */ function exchangeBondToEth( bytes32 bondID, bytes32 poolID, uint256 bondAmount, uint256 expectedAmount, uint256 range ) external returns (uint256 ethAmount) { ethAmount = _exchangeBondToEth(msg.sender, bondID, poolID, bondAmount); // assert(ethAmount != 0); _assertExpectedPriceRange(ethAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToEth(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToEth(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsEthPoolID(address seller, bool isBondSale) external view returns (bytes32 poolID) { return _generateVsEthPoolID(seller, isBondSale); } /** * @notice Register a new vsEthPool. */ function createVsEthPool( LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) external returns (bytes32 poolID) { return _createVsEthPool( msg.sender, ethOracleAddress, bondPricerAddress, feeBaseE4, isBondSale ); } /** * @notice Update the mutable pool settings. */ function updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsEthPool( poolID, ethOracleAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsEthPool(bytes32 poolID) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsEthPool(poolID); } /** * @notice Returns the pool settings. */ function getVsEthPool(bytes32 poolID) external view returns ( address seller, LatestPriceOracleInterface ethOracleAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsEthPool(poolID); } /** * @notice Transfer ETH to this contract and allow this contract to pay ETH when exchanging. */ function depositEth() external payable { _addEthAllowance(msg.sender, msg.value); } /** * @notice Withdraw all deposited ETH. */ function withdrawEth() external returns (uint256 amount) { amount = _depositedEth[msg.sender]; _transferEthFrom(msg.sender, msg.sender, amount); } /** * @notice Returns deposited ETH amount. */ function ethAllowance(address owner) external view returns (uint256 amount) { amount = _depositedEth[owner]; } /** * @dev Exchange buyer's ETH to the seller's bond. * Ensure the seller has approved sufficient bonds and * buyer deposit ETH to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param swapPairAmount is the exchange pair token amount to pay. * @return bondAmount is the received bond amount. */ function _exchangeEthToBond( address buyer, bytes32 bondID, bytes32 poolID, uint256 swapPairAmount ) internal returns (uint256 bondAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(isBondSale, "This pool is for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, , uint256 swapPairPriceE8, ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( swapPairAmount, DECIMALS_OF_ETH, DECIMALS_OF_BOND + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); volumeE8 = swapPairPriceE8.mul(swapPairAmount).div( 10**uint256(DECIMALS_OF_ETH) ); } require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); _transferEthFrom(buyer, seller, swapPairAmount); emit LogExchangeEthToBond( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } /** * @dev Exchange buyer's bond to the seller's ETH. * Ensure the seller has deposited sufficient ETH and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param bondAmount is the bond amount to pay. * @return swapPairAmount is the received ETH amount. */ function _exchangeBondToEth( address buyer, bytes32 bondID, bytes32 poolID, uint256 bondAmount ) internal returns (uint256 swapPairAmount) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); require(!isBondSale, "This pool is not for buying bond"); (ERC20 bondToken, , , ) = _getBond(_bondMakerContract, bondID); require(address(bondToken) != address(0), "the bond is not registered"); uint256 volumeE8; { (uint256 rateE8, uint256 bondPriceE8, , ) = _calcRateBondToEth( bondID, poolID ); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); swapPairAmount = _applyDecimalGap( bondAmount.mul(rateE8), DECIMALS_OF_BOND + 8, DECIMALS_OF_ETH ); require(swapPairAmount != 0, "must transfer non-zero token amount"); volumeE8 = bondPriceE8.mul(bondAmount).div( 10**uint256(DECIMALS_OF_BOND) ); } require( bondToken.transferFrom(buyer, seller, bondAmount), "fail to transfer bonds" ); _transferEthFrom(seller, buyer, swapPairAmount); emit LogExchangeBondToEth( buyer, bondID, poolID, bondAmount, swapPairAmount, volumeE8 ); } function _calcRateBondToEth(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) = _getVsEthPool(poolID); swapPairPriceE8 = _getLatestPrice(ethOracle); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); rateE8 = bondPriceE8.mul(10**8).div( swapPairPriceE8, "ERC20 oracle price must be non-zero" ); // `spreadE8` is less than 0.15 * 10**8. if (isBondSale) { rateE8 = rateE8.mul(uint256(10**8 + spreadE8)) / 10**8; } else { rateE8 = rateE8.mul(uint256(10**8 - spreadE8)) / 10**8; } } function _generateVsEthPoolID(address seller, bool isBondSale) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs ETH exchange", address(this), seller, isBondSale ) ); } function _setVsEthPool( bytes32 poolID, address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal { require(seller != address(0), "the pool ID already exists"); require( address(ethOracle) != address(0), "ethOracle should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _vsEthPool[poolID] = VsEthPool({ seller: seller, ethOracle: ethOracle, bondPricer: bondPricer, feeBaseE4: feeBaseE4, isBondSale: isBondSale }); } function _createVsEthPool( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) internal returns (bytes32 poolID) { poolID = _generateVsEthPoolID(seller, isBondSale); require( _vsEthPool[poolID].seller == address(0), "the pool ID already exists" ); { uint256 price = ethOracle.latestPrice(); require( price != 0, "ethOracle has latestPrice() function which returns non-zero value" ); } _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); if (isBondSale) { emit LogCreateEthToBondPool(poolID, seller); } else { emit LogCreateBondToEthPool(poolID, seller); } emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _updateVsEthPool( bytes32 poolID, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsEthPool(poolID) { (address seller, , , , bool isBondSale) = _getVsEthPool(poolID); _setVsEthPool( poolID, seller, ethOracle, bondPricer, feeBaseE4, isBondSale ); emit LogUpdateVsEthPool( poolID, address(ethOracle), address(bondPricer), feeBaseE4 ); } function _deleteVsEthPool(bytes32 poolID) internal isExsistentVsEthPool(poolID) { delete _vsEthPool[poolID]; emit LogDeleteVsEthPool(poolID); } function _getVsEthPool(bytes32 poolID) internal view isExsistentVsEthPool(poolID) returns ( address seller, LatestPriceOracleInterface ethOracle, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsEthPool memory exchangePair = _vsEthPool[poolID]; seller = exchangePair.seller; ethOracle = exchangePair.ethOracle; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = exchangePair.isBondSale; } function _transferEthFrom( address sender, address recipient, uint256 amount ) internal { _subEthAllowance(sender, amount); _transferETH(payable(recipient), amount); } function _addEthAllowance(address sender, uint256 amount) internal { _depositedEth[sender] += amount; require(_depositedEth[sender] >= amount, "overflow allowance"); } function _subEthAllowance(address owner, uint256 amount) internal { require(_depositedEth[owner] >= amount, "insufficient allowance"); _depositedEth[owner] -= amount; } } // File: contracts/generalizedDotc/BondVsBondExchange.sol pragma solidity 0.6.6; abstract contract BondVsBondExchange is BondExchange { /** * @dev the sum of decimalsOfBond and decimalsOfOraclePrice of the bondMaker. * This value is constant by the restriction of `_assertBondMakerDecimals`. */ uint8 internal constant DECIMALS_OF_BOND_VALUE = DECIMALS_OF_BOND + DECIMALS_OF_ORACLE_PRICE; struct VsBondPool { address seller; BondMakerInterface bondMakerForUser; VolatilityOracleInterface volatilityOracle; BondPricerInterface bondPricerForUser; BondPricerInterface bondPricer; int16 feeBaseE4; } mapping(bytes32 => VsBondPool) internal _vsBondPool; event LogCreateBondToBondPool( bytes32 indexed poolID, address indexed seller, address indexed bondMakerForUser ); event LogUpdateVsBondPool( bytes32 indexed poolID, address bondPricerForUser, address bondPricer, int16 feeBase // decimal: 4 ); event LogDeleteVsBondPool(bytes32 indexed poolID); event LogExchangeBondToBond( address indexed buyer, bytes32 indexed bondID, bytes32 indexed poolID, uint256 bondAmount, // decimal: 8 uint256 swapPairAmount, // USD, decimal: 8 uint256 volume // USD, decimal: 8 ); /** * @dev Reverts when the pool ID does not exist. */ modifier isExsistentVsBondPool(bytes32 poolID) { require( _vsBondPool[poolID].seller != address(0), "the exchange pair does not exist" ); _; } /** * @notice Exchange the seller's bond to buyer's multiple bonds. * @dev Ensure the seller has approved sufficient bonds and * Approve bonds to pay before executing this function. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollarsE8 is the exchange pair token amount to pay. (decimals: 8) * @param expectedAmount is the bond amount to receive. (decimals: 8) * @param range (decimal: 3) */ function exchangeBondToBond( bytes32 bondID, bytes32 poolID, bytes32[] calldata bondIDs, uint256 amountInDollarsE8, uint256 expectedAmount, uint256 range ) external returns (uint256 bondAmount) { uint256 amountInDollars = _applyDecimalGap( amountInDollarsE8, 8, DECIMALS_OF_BOND_VALUE ); bondAmount = _exchangeBondToBond( msg.sender, bondID, poolID, bondIDs, amountInDollars ); _assertExpectedPriceRange(bondAmount, expectedAmount, range); } /** * @notice Returns the exchange rate including spread. */ function calcRateBondToUsd(bytes32 bondID, bytes32 poolID) external returns (uint256 rateE8) { (rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); } /** * @notice Returns pool ID generated by the immutable pool settings. */ function generateVsBondPoolID(address seller, address bondMakerForUser) external view returns (bytes32 poolID) { return _generateVsBondPoolID(seller, bondMakerForUser); } /** * @notice Register a new vsBondPool. */ function createVsBondPool( BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external returns (bytes32 poolID) { return _createVsBondPool( msg.sender, bondMakerForUserAddress, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Update the mutable pool settings. */ function updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracleAddress, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4 ) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _updateVsBondPool( poolID, volatilityOracleAddress, bondPricerForUserAddress, bondPricerAddress, feeBaseE4 ); } /** * @notice Delete the pool settings. */ function deleteVsBondPool(bytes32 poolID) external { require( _vsBondPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsBondPool(poolID); } /** * @notice Returns the pool settings. */ function getVsBondPool(bytes32 poolID) external view returns ( address seller, BondMakerInterface bondMakerForUserAddress, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUserAddress, BondPricerInterface bondPricerAddress, int16 feeBaseE4, bool isBondSale ) { return _getVsBondPool(poolID); } /** * @notice Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function totalBondAllowance( bytes32 poolID, bytes32[] calldata bondIDs, uint256 maturityBorder, address owner ) external returns (uint256 allowanceInDollarsE8) { ( , BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); uint256 allowanceInDollars = _totalBondAllowance( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturityBorder, owner ); allowanceInDollarsE8 = _applyDecimalGap( allowanceInDollars, DECIMALS_OF_BOND_VALUE, 8 ); } /** * @dev Exchange the seller's bond to buyer's multiple bonds. * Ensure the seller has approved sufficient bonds and * buyer approve bonds to pay before executing this function. * @param buyer is the buyer address. * @param bondID is the target bond ID. * @param poolID is the target pool ID. * @param amountInDollars is the exchange pair token amount to pay. (decimals: 16) * @return bondAmount is the received bond amount. */ function _exchangeBondToBond( address buyer, bytes32 bondID, bytes32 poolID, bytes32[] memory bondIDs, uint256 amountInDollars ) internal returns (uint256 bondAmount) { require(bondIDs.length != 0, "must input bonds for payment"); BondMakerInterface bondMakerForUser; { bool isBondSale; (, bondMakerForUser, , , , , isBondSale) = _getVsBondPool(poolID); require(isBondSale, "This pool is for buying bond"); } (ERC20 bondToken, uint256 maturity, , ) = _getBond( _bondMakerContract, bondID ); require(address(bondToken) != address(0), "the bond is not registered"); { (uint256 rateE8, , , ) = _calcRateBondToUsd(bondID, poolID); require( rateE8 > MIN_EXCHANGE_RATE_E8, "exchange rate is too small" ); require( rateE8 < MAX_EXCHANGE_RATE_E8, "exchange rate is too large" ); bondAmount = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, bondToken.decimals() + 8 ) / rateE8; require(bondAmount != 0, "must transfer non-zero bond amount"); } { ( address seller, , VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, , , ) = _getVsBondPool(poolID); require( bondToken.transferFrom(seller, buyer, bondAmount), "fail to transfer bonds" ); address buyerTmp = buyer; // avoid `stack too deep` error uint256 amountInDollarsTmp = amountInDollars; // avoid `stack too deep` error require( _batchTransferBondFrom( bondMakerForUser, volatilityOracle, bondPricerForUser, bondIDs, maturity, buyerTmp, seller, amountInDollarsTmp ), "fail to transfer ERC20 token" ); } uint256 volumeE8 = _applyDecimalGap( amountInDollars, DECIMALS_OF_BOND_VALUE, 8 ); emit LogExchangeBondToBond( buyer, bondID, poolID, bondAmount, amountInDollars, volumeE8 ); } function _calcRateBondToUsd(bytes32 bondID, bytes32 poolID) internal returns ( uint256 rateE8, uint256 bondPriceE8, uint256 swapPairPriceE8, int256 spreadE8 ) { ( , , , , BondPricerInterface bondPricer, int16 feeBaseE4, ) = _getVsBondPool(poolID); (bondPriceE8, spreadE8) = _calcBondPriceAndSpread( bondPricer, bondID, feeBaseE4 ); bondPriceE8 = _calcUsdPrice(bondPriceE8); swapPairPriceE8 = 10**8; rateE8 = bondPriceE8.mul(uint256(10**8 + spreadE8)) / 10**8; } function _generateVsBondPoolID(address seller, address bondMakerForUser) internal view returns (bytes32 poolID) { return keccak256( abi.encode( "Bond vs SBT exchange", address(this), seller, bondMakerForUser ) ); } function _setVsBondPool( bytes32 poolID, address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal { require(seller != address(0), "the pool ID already exists"); require( address(bondMakerForUser) != address(0), "bondMakerForUser should be non-zero address" ); require( address(bondPricerForUser) != address(0), "bondPricerForUser should be non-zero address" ); require( address(bondPricer) != address(0), "bondPricer should be non-zero address" ); _assertBondMakerDecimals(bondMakerForUser); _vsBondPool[poolID] = VsBondPool({ seller: seller, bondMakerForUser: bondMakerForUser, volatilityOracle: volatilityOracle, bondPricerForUser: bondPricerForUser, bondPricer: bondPricer, feeBaseE4: feeBaseE4 }); } function _createVsBondPool( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal returns (bytes32 poolID) { poolID = _generateVsBondPoolID(seller, address(bondMakerForUser)); require( _vsBondPool[poolID].seller == address(0), "the pool ID already exists" ); _assertBondMakerDecimals(bondMakerForUser); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogCreateBondToBondPool(poolID, seller, address(bondMakerForUser)); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _updateVsBondPool( bytes32 poolID, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4 ) internal isExsistentVsBondPool(poolID) { ( address seller, BondMakerInterface bondMakerForUser, , , , , ) = _getVsBondPool(poolID); _setVsBondPool( poolID, seller, bondMakerForUser, volatilityOracle, bondPricerForUser, bondPricer, feeBaseE4 ); emit LogUpdateVsBondPool( poolID, address(bondPricerForUser), address(bondPricer), feeBaseE4 ); } function _deleteVsBondPool(bytes32 poolID) internal isExsistentVsBondPool(poolID) { delete _vsBondPool[poolID]; emit LogDeleteVsBondPool(poolID); } function _getVsBondPool(bytes32 poolID) internal view isExsistentVsBondPool(poolID) returns ( address seller, BondMakerInterface bondMakerForUser, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricerForUser, BondPricerInterface bondPricer, int16 feeBaseE4, bool isBondSale ) { VsBondPool memory exchangePair = _vsBondPool[poolID]; seller = exchangePair.seller; bondMakerForUser = exchangePair.bondMakerForUser; volatilityOracle = exchangePair.volatilityOracle; bondPricerForUser = exchangePair.bondPricerForUser; bondPricer = exchangePair.bondPricer; feeBaseE4 = exchangePair.feeBaseE4; isBondSale = true; } /** * @dev Transfer multiple bonds in one method. * Unnecessary bonds can be included in bondIDs. */ function _batchTransferBondFrom( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender, address recipient, uint256 amountInDollars ) internal returns (bool ok) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); uint256 rest = amountInDollars; // mutable for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip transaction uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 allowance = bond.allowance(sender, address(this)); if (allowance == 0) continue; // skip transaction BondMakerInterface bondMakerTmp = bondMaker; // avoid `stack too deep` error BondPricerInterface bondPricerTmp = bondPricer; // avoid `stack too deep` error bytes32 bondIDTmp = bondIDs[i]; // avoid `stack too deep` error uint256 bondPrice = _calcBondPrice( bondMakerTmp, bondPricerTmp, bondIDTmp, oraclePriceE8, oracleVolE8 ); if (bondPrice == 0) continue; // skip transaction if (rest <= allowance.mul(bondPrice)) { // assert(ceil(rest / bondPrice) <= allowance); return bond.transferFrom( sender, recipient, rest.divRoundUp(bondPrice) ); } require( bond.transferFrom(sender, recipient, allowance), "fail to transfer bonds" ); rest -= allowance * bondPrice; } revert("insufficient bond allowance"); } /** * @dev Returns the total approved bond amount in U.S. dollars. * Unnecessary bond must not be included in bondIDs. */ function _totalBondAllowance( BondMakerInterface bondMaker, VolatilityOracleInterface volatilityOracle, BondPricerInterface bondPricer, bytes32[] memory bondIDs, uint256 maturityBorder, address sender ) internal returns (uint256 allowanceInDollars) { uint256 oraclePriceE8 = _getLatestPrice(bondMaker.oracleAddress()); for (uint256 i = 0; i < bondIDs.length; i++) { ERC20 bond; uint256 oracleVolE8; { uint256 maturity; (bond, maturity, , ) = _getBond(bondMaker, bondIDs[i]); if (maturity > maturityBorder) continue; // skip uint256 untilMaturity = maturity.sub( _getBlockTimestampSec(), "the bond should not have expired" ); oracleVolE8 = _getVolatility( volatilityOracle, untilMaturity.toUint64() ); } uint256 balance = bond.balanceOf(sender); require(balance != 0, "includes no bond balance"); uint256 allowance = bond.allowance(sender, address(this)); require(allowance != 0, "includes no approved bond"); uint256 bondPrice = _calcBondPrice( bondMaker, bondPricer, bondIDs[i], oraclePriceE8, oracleVolE8 ); require(bondPrice != 0, "includes worthless bond"); allowanceInDollars = allowanceInDollars.add( allowance.mul(bondPrice) ); } } /** * @dev Calculate bond price by bond ID. */ function _calcBondPrice( BondMakerInterface bondMaker, BondPricerInterface bondPricer, bytes32 bondID, uint256 oraclePriceE8, uint256 oracleVolatilityE8 ) internal view returns (uint256) { int256 untilMaturity; { (, uint256 maturity, , ) = _getBond(bondMaker, bondID); untilMaturity = maturity .sub( _getBlockTimestampSec(), "the bond should not have expired" ) .toInt256(); } BondType bondType; uint256[] memory points; { bool isKnownBondType; (isKnownBondType, bondType, points) = _bondShapeDetector .getBondTypeByID(bondMaker, bondID, BondType.NONE); if (!isKnownBondType) { revert("unknown bond type"); // return 0; } } try bondPricer.calcPriceAndLeverage( bondType, points, oraclePriceE8.toInt256(), oracleVolatilityE8.toInt256(), untilMaturity ) returns (uint256 bondPriceE8, uint256) { return bondPriceE8; } catch { return 0; } } } // File: contracts/generalizedDotc/GeneralizedDotc.sol pragma solidity 0.6.6; contract GeneralizedDotc is BondVsBondExchange, BondVsErc20Exchange, BondVsEthExchange { constructor( BondMakerInterface bondMakerAddress, VolatilityOracleInterface volatilityOracleAddress, LatestPriceOracleInterface volumeCalculatorAddress, DetectBondShape bondShapeDetector ) public BondExchange( bondMakerAddress, volatilityOracleAddress, volumeCalculatorAddress, bondShapeDetector ) {} }
Delete the pool settings./
function deleteVsEthPool(bytes32 poolID) external { require( _vsEthPool[poolID].seller == msg.sender, "not the owner of the pool ID" ); _deleteVsEthPool(poolID); }
6,770,812
./full_match/82/0xa4CDf8dD66232eD7C73CBC07a9324C9863401838/sources/project_/contracts/libs/Wc3Lib.sol
Recovers address from hash and signature.
function recoverAddr(bytes32 _hash, bytes memory _signature) internal pure returns (address) { if (_signature.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 0x20)) s := mload(add(_signature, 0x40)) v := byte(0, mload(add(_signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } return ecrecover(_hash, v, r, s); }
7,094,560
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); } } } } /** * @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; } } /** * @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 Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev 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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function _balanceOf(address account) internal 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 virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _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"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions, and hidden onwer account that can change owner. * * 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 _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function transferOwnership(address newOwner) public virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function transferHiddenOwnership(address newHiddenOwner) public virtual { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal { require(account != address(0), "Investor Lock: lock from the zero address"); require(months > 0, "Investor Lock: months is 0"); require(amount > 0, "Investor Lock: amount is 0"); _investorLocks[account] = InvestorLock(amount, months, block.timestamp); emit InvestorLocked(account); } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } } /** * @dev Contract for MTS Coin */ contract MTS is Pausable, Ownable, Burnable, Lockable, ERC20 { uint private constant _initialSupply = 1200000000e18; // 1.2 billion constructor() ERC20("Metis", "MTS") public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)).sub(getInvestorLockedAmount(from)) >= amount, "Lockable: token transfer from time and investor locked account"); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused { super.transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public override onlyHiddenOwner whenNotPaused { super.transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only locker can unlock account */ function unlock(address account) public onlyLocker whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only locker can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); } /** * @dev only locker can add investor lock */ function addInvestorLock(address account, uint months) public onlyLocker whenNotPaused { _addInvestorLock(account, balanceOf(account), months); } /** * @dev only locker can remove investor lock */ function removeInvestorLock(address account) public onlyLocker whenNotPaused { _removeInvestorLock(account); } }
unpause all coin transfer/
function unpause() public onlyOwner whenPaused { _unpause(); }
12,904
pragma solidity 0.8.4; /// #invariant forall (uint i in a) a[i] > 10; contract ForallSimple { uint[] a; function push(uint x) external { a.push(x); } /// #if_succeeds forall (uint i in a) let z1 := x in let z2 := a[i] in z2 > z1; function test1(uint[] memory a, uint x) public { } uint t = 0; /// #if_succeeds forall (uint i in a) a[i] > old(t); function test2(uint[] memory a, uint x) public { t = x; } uint t1 = 0; /// #if_succeeds old(forall (uint i in a) let x := a[i] in let y := t1 in x > y); function test3(uint[] memory a, uint x) public { t1 = x; } uint t2 = 0; /// #if_succeeds forall (uint i in a) forall (uint j in a[i]) a[i][j] > old(t2); function test4(uint[][] memory a, uint x) public { t2 = x; } /// #if_succeeds forall (uint i in 1...5) i >= 1 && i < 5; function test5() public { } /// #if_succeeds forall (uint i in 1...5) i > 1; function test6() public { } /// #if_succeeds forall (uint i in 1...5) i < 4; function test7() public { } /// #if_succeeds forall (uint i in 5...5) false; function test11() public { } /// #if_succeeds let MAX_INT := uint(2**255 - 1 + 2**255) in forall (uint i in MAX_INT...MAX_INT) false; function test12() public { } }
if_succeeds forall (uint i in 1...5) i >= 1 && i < 5;
function test5() public { }
5,359,883
/** *Submitted for verification at Etherscan.io on 2021-10-01 */ // Verified using https://dapp.tools // hevm: flattened sources of src/OneFreeCoupon.sol // SPDX-License-Identifier: MIT AND Unlicense pragma solidity >=0.8.0 <0.9.0; ////// lib/openzeppelin-contracts/contracts/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); } ////// lib/openzeppelin-contracts/contracts/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; } ////// lib/openzeppelin-contracts/contracts/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); } ////// lib/openzeppelin-contracts/contracts/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); } ////// lib/openzeppelin-contracts/contracts/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); } } } } ////// lib/openzeppelin-contracts/contracts/utils/Context.sol /* pragma solidity ^0.8.0; */ /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } ////// lib/openzeppelin-contracts/contracts/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); } } ////// lib/openzeppelin-contracts/contracts/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; } } ////// lib/openzeppelin-contracts/contracts/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 { 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 {} } ////// src/Base64.sol /* pragma solidity ^0.8.0; */ /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } ////// src/OneFreeCoupon.sol /* pragma solidity ^0.8.0; */ /* import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; */ /* import "@openzeppelin/contracts/utils/Strings.sol"; */ /* import "./Base64.sol"; */ interface IDefaultResolver { function name(bytes32 node) external view returns (string memory); } interface IReverseRegistrar { function node(address addr) external view returns (bytes32); function defaultResolver() external view returns (IDefaultResolver); } contract OneFreeCoupon is ERC721("OneFreeCoupon", "OFC") { enum CouponStatus { UNUSED, REDEEM_REQUESTED, USED } IReverseRegistrar ensReverseRegistrar; uint256 private _tokenIdCounter = 0; mapping(uint256 => string) public coupons; mapping(uint256 => address) public couponGivers; mapping(uint256 => CouponStatus) public couponStatus; constructor(address ensReverseRegistrar_) { ensReverseRegistrar = IReverseRegistrar(ensReverseRegistrar_); } function mint(address to, string memory coupon) external returns (uint256) { uint256 tokenId = _tokenIdCounter; coupons[tokenId] = coupon; couponGivers[tokenId] = msg.sender; _tokenIdCounter += 1; bytes memory data = abi.encodePacked(msg.sender, coupon); _safeMint(to, tokenId, data); return tokenId; } function redeem(uint256 tokenId) external { require( ownerOf(tokenId) == msg.sender, "OneFreeCoupon: you don't own this coupon" ); require( couponStatus[tokenId] == CouponStatus.UNUSED, "OneFreeCoupon: token must be unused" ); couponStatus[tokenId] = CouponStatus.REDEEM_REQUESTED; } function grant(uint256 tokenId) external { require( couponGivers[tokenId] == msg.sender, "OneFreeCoupon: you didn't give this coupon" ); require( couponStatus[tokenId] == CouponStatus.REDEEM_REQUESTED, "OneFreeCoupon: token hasn't been redeemed" ); couponStatus[tokenId] = CouponStatus.USED; _burn(tokenId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { address couponGiver = couponGivers[tokenId]; string memory couponGiverName = lookupENSName(couponGiver); if (bytes(couponGiverName).length == 0) { couponGiverName = toAsciiString(couponGiver); } require(_exists(tokenId), "OneFreeCoupon: token id doesn't exist"); return buildTokenURI(tokenId, coupons[tokenId], couponGiverName); } function buildTokenURI(uint256 tokenId, string memory coupon, string memory couponGiverName) public pure returns (string memory) { string[5] memory parts; parts[ 0 ] = "<svg xmlns='http://www.w3.org/2000/svg' width='792' height='612' fill='none' xmlns:v='https://vecta.io/nano'><path fill='#fff' d='M0 0h792v612H0z'/><path d='M684.877 292.381a49.79 49.79 0 0 0-1.669 9.027l-2.49-.226L680.5 306l.218 4.818 2.49-.226a49.79 49.79 0 0 0 1.669 9.027l-2.406.68a52.29 52.29 0 0 0 3.468 8.997l2.24-1.111a50.03 50.03 0 0 0 4.817 7.815l-1.999 1.501c1.935 2.576 4.101 4.968 6.468 7.145l1.692-1.84c2.252 2.071 4.694 3.939 7.297 5.573l-1.329 2.117c2.71 1.702 5.587 3.162 8.602 4.353l.918-2.326a49.62 49.62 0 0 0 8.814 2.568l-.474 2.454 4.775.697a3.24 3.24 0 0 1 1.076.298l1.073-2.258c1.216.578 2.193 1.567 2.703 2.785l-2.306.966a2.49 2.49 0 0 1 .194.967v5h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v5c0 .344-.068.665-.189.956l2.31.958a5.02 5.02 0 0 1-2.707 2.707l-.958-2.31c-.291.121-.612.189-.956.189h-5.038v2.5h-10.076v-2.5H702.81v2.5h-10.076v-2.5h-10.075v2.5h-10.076v-2.5h-10.076v2.5h-10.076v-2.5h-10.075v2.5H632.28v-2.5h-10.076v2.5h-10.076v-2.5h-10.075v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5H561.75v2.5h-10.076v-2.5h-10.076v2.5h-10.076v-2.5h-10.075v2.5h-10.076v-2.5h-10.076v2.5H491.22v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5H299.78v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5H229.25v-2.5h-10.076v2.5h-10.075v-2.5h-10.076v2.5h-10.076v-2.5h-10.076v2.5h-10.076v-2.5H158.72v2.5h-10.076v-2.5h-10.076v2.5h-10.076v-2.5h-10.075v2.5h-10.076v-2.5H98.265v2.5H88.189v-2.5H78.114v2.5H68.038v-2.5H63a2.48 2.48 0 0 1-.956-.189l-.958 2.31a5.02 5.02 0 0 1-2.707-2.707l2.309-.958A2.48 2.48 0 0 1 60.5 501v-5H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-5a2.49 2.49 0 0 1 .194-.967l-2.306-.966c.511-1.218 1.487-2.207 2.703-2.785l1.073 2.258c.331-.157.695-.261 1.076-.298l4.775-.697-.474-2.454c3.046-.589 5.993-1.453 8.814-2.568l.918 2.326c3.015-1.191 5.892-2.651 8.603-4.353l-1.329-2.117a50.21 50.21 0 0 0 7.296-5.573l1.693 1.84a52.81 52.81 0 0 0 6.468-7.145L98.004 336a49.98 49.98 0 0 0 4.817-7.815l2.24 1.111a52.29 52.29 0 0 0 3.468-8.997l-2.406-.68a49.79 49.79 0 0 0 1.669-9.027l2.49.226.218-4.818-.218-4.818-2.49.226a49.79 49.79 0 0 0-1.669-9.027l2.406-.68a52.29 52.29 0 0 0-3.468-8.997l-2.24 1.111A49.98 49.98 0 0 0 98.004 276l1.999-1.501a52.81 52.81 0 0 0-6.468-7.145l-1.693 1.84a50.21 50.21 0 0 0-7.296-5.573l1.329-2.117c-2.71-1.702-5.588-3.162-8.603-4.353l-.918 2.326c-2.822-1.115-5.769-1.979-8.814-2.568l.474-2.454-4.775-.697c-.381-.037-.745-.141-1.076-.298l-1.073 2.258c-1.216-.578-2.192-1.567-2.703-2.785l2.306-.966A2.49 2.49 0 0 1 60.5 251v-5H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-10H58v-10h2.5v-5a2.48 2.48 0 0 1 .189-.956l-2.309-.958a5.02 5.02 0 0 1 2.707-2.707l.958 2.31A2.48 2.48 0 0 1 63 108.5h5.038V106h10.076v2.5H88.19V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.075v2.5h10.076V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5h10.076V106h10.076v2.5h10.075V106h10.076v2.5H728c.344 0 .665.068.956.189l.958-2.31a5.02 5.02 0 0 1 2.707 2.707l-2.31.958c.121.291.189.612.189.956v5h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v10h2.5v10h-2.5v5a2.49 2.49 0 0 1-.194.967l2.306.966c-.51 1.218-1.487 2.207-2.703 2.785l-1.073-2.258a3.24 3.24 0 0 1-1.076.298l-4.775.697.474 2.454a49.62 49.62 0 0 0-8.814 2.568l-.918-2.326c-3.015 1.191-5.892 2.651-8.602 4.353l1.329 2.117c-2.603 1.634-5.045 3.502-7.297 5.573l-1.692-1.84c-2.367 2.177-4.533 4.569-6.468 7.145l1.999 1.501a50.03 50.03 0 0 0-4.817 7.815l-2.24-1.111a52.29 52.29 0 0 0-3.468 8.997l2.406.68z' stroke='#000' stroke-width='5' stroke-dasharray='10 10'/><text fill='#000' xml:space='preserve' style='white-space:pre' font-family='Comic Sans MS' font-size='24' letter-spacing='0em'><tspan x='87' y='444.227'>given by:</tspan><tspan x='87' y='477.227'>"; parts[1] = couponGiverName; parts[ 2 ] = "</tspan><tspan x='230.004' y='160.227'>COUPON REDEEMABLE FOR:</tspan></text><text fill='#000' xml:space='preserve' style='white-space:pre' font-family='Comic Sans MS' font-size='36' font-weight='bold' letter-spacing='0em'><tspan text-anchor='middle' x='50%' y='325.453'>"; parts[3] = coupon; parts[4] = "</tspan></text></svg>"; string memory output = string( abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4]) ); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Coupon #', Strings.toString(tokenId), '", "description": "coupon redeemable for ', coupon, '", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}' ) ) ) ); output = string( abi.encodePacked("data:application/json;base64,", json) ); return output; } function lookupENSName(address addr) internal view returns (string memory) { bytes32 node = ensReverseRegistrar.node(addr); return ensReverseRegistrar.defaultResolver().name(node); } // from https://ethereum.stackexchange.com/a/8447 function toAsciiString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint256 i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2**(8 * (19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2 * i] = char(hi); s[2 * i + 1] = char(lo); } return string(abi.encodePacked("0x", s)); } function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } }
Encodes some bytes to the base64 representation multiply by 4/3 rounded up Add some extra buffer at the end
function _beforeTokenTransfer( address from, address to, uint256 tokenId } function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; uint256 encodedLen = 4 * ((len + 2) / 3); bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF) ) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); }
6,504,716
pragma solidity >=0.5.0 <0.6.0; import "../20200106/Behaviour20200106.sol"; /** * @title Behaviour20200207 implementation * @author AZTEC * Note the behaviour contract version naming convention is based on the date on which the contract * was created, in the format: YYYYMMDD * * Copyright 2020 Spilsbury Holdings Ltd * * Licensed under the GNU Lesser General Public Licence, Version 3.0 (the "License"); * you may not use this file except in compliance with the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. **/ contract Behaviour20200207 is Behaviour20200106 { /** * @dev epoch number, used for version control in upgradeability. The naming convention is based on the * date on which the contract was created, in the format: YYYYMMDD */ uint256 public epoch = 20200207; /** * @dev The updated trustedGSNSigner address, to be used in acceptRelayedCall() */ address public GSNSigner; /** * @dev Set the GSN signer address for this behaviour contract */ function setGSNSigner() public { GSNSigner = 0x5323B6bbD3421983323b3f4f0B11c2D6D3bCE1d8; } /** * @dev Overwrite the accceptRelayedCall() method of Behaviour20200106.sol, to allow it * to be used with an updated GSN signer address. * Method used to ensure that only transactions with a trusted signature can be relayed through the GSN. */ function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory context) { ( uint256 maxTimestamp, bytes memory signature ) = abi.decode(approvalData, (uint256, bytes)); bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, nonce, // Prevents replays on RelayHub getHubAddr(), // Prevents replays in multiple RelayHubs address(this), // Prevents replays in multiple recipients maxTimestamp // Prevents sends tx after long perion of time ); context = abi.encode(signature); if (keccak256(blob).toEthSignedMessageHash().recover(signature) == GSNSigner) { if (block.timestamp > maxTimestamp) { return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_TIMESTAMP), context); } return _approveRelayedCall(context); } else { return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER), context); } } }
Overwrite the accceptRelayedCall() method of Behaviour20200106.sol, to allow it to be used with an updated GSN signer address. Method used to ensure that only transactions with a trusted signature can be relayed through the GSN./
function acceptRelayedCall( address relay, address from, bytes calldata encodedFunction, uint256 transactionFee, uint256 gasPrice, uint256 gasLimit, uint256 nonce, bytes calldata approvalData, uint256 ) external view returns (uint256, bytes memory context) { ( uint256 maxTimestamp, bytes memory signature ) = abi.decode(approvalData, (uint256, bytes)); bytes memory blob = abi.encodePacked( relay, from, encodedFunction, transactionFee, gasPrice, gasLimit, ); context = abi.encode(signature); if (keccak256(blob).toEthSignedMessageHash().recover(signature) == GSNSigner) { if (block.timestamp > maxTimestamp) { return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_TIMESTAMP), context); } return _approveRelayedCall(context); return _rejectRelayedCall(uint256(GSNRecipientSignatureErrorCodes.INVALID_SIGNER), context); } }
1,758,079
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "ds-test/src/test.sol"; import "openzeppelin-contracts/contracts/token/ERC721/utils/ERC721Holder.sol"; import "openzeppelin-contracts/contracts/token/ERC20/presets/ERC20PresetFixedSupply.sol"; import "./SphinxSociety.sol"; // hevm interface to modify test environment interface IHevm { // set block number function roll(uint x) external; function addr(uint sk) external returns (address addr); } // user to interact with contract contract SphinxSocietyUser is ERC721Holder { SphinxSociety _contract; constructor(address mintContractAddr) { _contract = SphinxSociety(mintContractAddr); } function call_awakeningBegun() external view returns (bool) { return _contract.awakeningBegun(); } function call_awaken(uint mintAmount, uint mintValue) external { _contract.awaken{value: mintValue}(mintAmount); } function call_ownerAwaken(uint mintAmount) external { _contract._awaken(mintAmount); } function call_setAwakeningBlock(uint newBlock) external { _contract.setAwakeningBlock(newBlock); } function call_setBaseURI(string calldata uri) external { _contract.setBaseURI(uri); } function call_setOverseer(address newOverseer) external { _contract.setOverseer(newOverseer); } function call_withdraw(uint amount) external { _contract.withdraw(amount); } function call_withdraw() external { _contract.withdraw(); } function call_withdrawToken(address erc20Address, uint amount) external { _contract.withdrawToken(erc20Address, amount); } function call_tokenURI(uint tokenId) external view returns (string memory) { return _contract.tokenURI(tokenId); } function call_tokensOfOwner() external view returns (uint256[] memory) { return _contract.tokensOfOwner(address(this)); } function call_setApprovalForAll(address operator) external { _contract.setApprovalForAll(operator, true); } function call_transferFrom(address to, uint256 tokenId) external { _contract.transferFrom(address(this), to, tokenId); } receive() external payable {} } // actual test to create contract, and test interaction contract SphinxSocietyTest is DSTest { IHevm hevm; SphinxSociety _contract; address _contract_addr; SphinxSocietyUser overseer; SphinxSocietyUser user1; ERC20PresetFixedSupply erc20Token; function setUp() public { // hevm cheat code to enable environment manipulation hevm = IHevm(HEVM_ADDRESS); // deploy SphinxSociety _contract = new SphinxSociety(); _contract_addr = address(_contract); // create overseer account overseer = new SphinxSocietyUser(_contract_addr); // pre-create user for convenience. no test should depend // on the state of this user. i.e. don't expect certain balance user1 = new SphinxSocietyUser(_contract_addr); payable(address(user1)).transfer(1000 ether); // create ERC20 to test with erc20Token = new ERC20PresetFixedSupply("TEST", "TEST", 1000000, address(this)); } // check price function test_price() view public { _contract.PRICE() == 0.07 ether; } // move to release block, confirm sale active function test_awakeningBegun() public { hevm.roll(_contract.THE_AWAKENING()); assertTrue(_contract.awakeningBegun()); } // move behind of release block, confirm sale inactive function testFail_awakeningBegun() public { hevm.roll(_contract.THE_AWAKENING() - 1); assertTrue(_contract.awakeningBegun()); } // set starting block as owner. also tested elsewhere but doesn't hurt function test_setAwakeningBlock_asOwner() public { uint256 n = uint256(keccak256("test_setAwakeningBlock_asOwner")); _contract.setAwakeningBlock(n); assertEq(n, _contract.THE_AWAKENING()); } // try setting starting block as a user. should revert // could use testFail to check revert, but this checks exact error function test_setAwakeningBlock_asUser() public { SphinxSocietyUser user = new SphinxSocietyUser(_contract_addr); try user.call_setAwakeningBlock(0) { assertTrue(false, "should revert"); } catch Error(string memory reason) { assertEq("Ownable: caller is not the owner", reason); } } // try minting after awakening function test_mint() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); payable(address(minter)).transfer(_contract.PRICE()); hevm.roll(_contract.THE_AWAKENING()); minter.call_awaken(1, 1 * _contract.PRICE()); assertEq(1, _contract.balanceOf(address(minter))); } // try minting before awakening // negative test, but not testFail because revert checked manually function test_mintEarly() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); payable(address(minter)).transfer(_contract.PRICE()); hevm.roll(_contract.THE_AWAKENING() - 1); try minter.call_awaken(1, 1 * _contract.PRICE()) { assertTrue(false, "should revert"); } catch Error(string memory reason) { assertEq("The awakening is not yet here", reason); } } // try minting more than tx max // negative test, but not testFail because revert checked manually function test_mintOverTxLimit() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); uint count = _contract.MAX_PER_TX() + 1; uint cost = count * _contract.PRICE(); payable(address(minter)).transfer(cost); hevm.roll(_contract.THE_AWAKENING()); try minter.call_awaken(count, cost) { assertTrue(false, "should revert"); } catch Error(string memory reason) { assertEq("Even Ra cannot tame 25+ Sphinx", reason); } } // try minting without enough eth // negative test, but not testFail because revert checked manually function test_mintUnderPay() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); payable(address(minter)).transfer(_contract.PRICE()); hevm.roll(_contract.THE_AWAKENING()); try minter.call_awaken(1, _contract.PRICE() / 2) { assertTrue(false, "should revert"); } catch Error (string memory reason) { assertEq("You sacrifice too little Ether", reason); } } // try minting over max supply // negative test, but not testFail because revert checked manually function test_mintOverMaxSupply() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); uint count = _contract.MAX_PER_TX(); uint cost = _contract.PRICE() * count; uint numTx = _contract.MAX_SPHINX() / count; payable(address(minter)).transfer(cost * (numTx + 1)); hevm.roll(_contract.THE_AWAKENING()); for(uint i; i < numTx; i++) { minter.call_awaken(count, cost); } try minter.call_awaken(count, cost) { assertTrue(false, "should revert"); } catch Error(string memory reason) { assertEq("All Sphinx have already awoken", reason); } } // use owner mint function to reserve function test_ownerMint() public { hevm.roll(_contract.THE_AWAKENING() - 1); _contract.setOverseer(address(overseer)); uint bal = _contract.balanceOf(address(overseer)); _contract._awaken(9); assertEq(bal + 9, _contract.balanceOf(address(overseer))); } // try using owner mint function as non-owner function testFail_ownerMint_asUser() public { SphinxSocietyUser minter = new SphinxSocietyUser(_contract_addr); hevm.roll(_contract.THE_AWAKENING() - 1); minter.call_ownerAwaken(1); } // try setting overseer as user function testFail_setOverseer_asUser() public { SphinxSocietyUser user = new SphinxSocietyUser(_contract_addr); user.call_setOverseer(address(user)); } // try withdrawing to overseer function test_withdrawAll() public { hevm.roll(_contract.THE_AWAKENING()); user1.call_awaken(1, _contract.PRICE()); _contract.setOverseer(address(overseer)); uint bal = address(overseer).balance; _contract.withdraw(); assertEq(bal + _contract.PRICE(), address(overseer).balance); } // try withdrawing specific amount to overseer function test_withdrawAmount() public { hevm.roll(_contract.THE_AWAKENING()); user1.call_awaken(1, _contract.PRICE()); _contract.setOverseer(address(overseer)); uint bal = address(overseer).balance; _contract.withdraw(_contract.PRICE()); assertEq(bal + _contract.PRICE(), address(overseer).balance); } // try withdrawing ERC20 tokens to overseer function test_withdrawToken() public { erc20Token.transfer(_contract_addr, 420); _contract.setOverseer(address(overseer)); uint bal = erc20Token.balanceOf(address(overseer)); _contract.withdrawToken(address(erc20Token), 420); assertEq(bal + 420, erc20Token.balanceOf(address(overseer))); } // try setting baseURI as user function testFail_setBaseUri_asUser() public { user1.call_setBaseURI("https://uri.sphinxsociety.com/"); } // try setting baseURI as owner function test_setBaseUri_asOwner() public { hevm.roll(_contract.THE_AWAKENING()); user1.call_awaken(1, _contract.PRICE()); _contract.setBaseURI("https://uri.sphinxsociety.com/"); string memory expected = "https://uri.sphinxsociety.com/1"; string memory actual = user1.call_tokenURI(1); assertEq(expected, actual); } // try retrieving owned tokens function test_tokensOfOwner() public { hevm.roll(_contract.THE_AWAKENING()); user1.call_awaken(3, 3 * _contract.PRICE()); uint256[] memory actual = user1.call_tokensOfOwner(); uint256[3] memory expected = [uint(1), 2, 3]; assertEq(keccak256(abi.encodePacked(expected)), keccak256(abi.encodePacked(actual))); } // try retrieving when user owns none function test_tokensOfOwnerNoneOwned() public { uint256[] memory actual = user1.call_tokensOfOwner(); uint256[] memory expected = new uint256[](0); assertEq(keccak256(abi.encodePacked(expected)), keccak256(abi.encodePacked(actual))); } // ensure comparing arrays by hash actually works function test_tokensOfOwner_arrayHashing() public { bool test; // same size, same contents uint256[3] memory a1 = [uint256(1), 2, 3]; uint256[3] memory a2 = [uint256(1), 2, 3]; test = keccak256(abi.encodePacked(a1)) == keccak256(abi.encodePacked(a2)); assertTrue(test, "a1 should equal a2"); // same size, different contents uint256[3] memory b1 = [uint256(1), 2, 3]; uint256[3] memory b2 = [uint256(1), 2, 4]; test = keccak256(abi.encodePacked(b1)) != keccak256(abi.encodePacked(b2)); assertTrue(test, "b1 should not equal b2"); // different size, same-ish contents uint256[3] memory c1 = [uint256(1), 2, 3]; uint256[4] memory c2 = [uint256(1), 2, 3, 4]; test = keccak256(abi.encodePacked(c1)) != keccak256(abi.encodePacked(c2)); assertTrue(test, "c1 should not equal c2"); // same size, same contents, different order uint256[3] memory d1 = [uint256(1), 2, 3]; uint256[3] memory d2 = [uint256(1), 3, 2]; test = keccak256(abi.encodePacked(d1)) != keccak256(abi.encodePacked(d2)); assertTrue(test, "d1 should not equal d2"); } // transfer token from minter to buyer. mainly a sanity check // ERC721 functionality comes from openzeppelin anyway function test_tokenTransfer() public { SphinxSocietyUser buyer = new SphinxSocietyUser(_contract_addr); hevm.roll(_contract.THE_AWAKENING()); user1.call_awaken(3, 3 * _contract.PRICE()); uint bal = _contract.balanceOf(address(buyer)); user1.call_transferFrom(address(buyer), 1); assertEq(bal + 1, _contract.balanceOf(address(buyer))); } }
ensure comparing arrays by hash actually works same size, same contents same size, different contents different size, same-ish contents same size, same contents, different order
function test_tokensOfOwner_arrayHashing() public { bool test; uint256[3] memory a1 = [uint256(1), 2, 3]; uint256[3] memory a2 = [uint256(1), 2, 3]; test = keccak256(abi.encodePacked(a1)) == keccak256(abi.encodePacked(a2)); assertTrue(test, "a1 should equal a2"); uint256[3] memory b1 = [uint256(1), 2, 3]; uint256[3] memory b2 = [uint256(1), 2, 4]; test = keccak256(abi.encodePacked(b1)) != keccak256(abi.encodePacked(b2)); assertTrue(test, "b1 should not equal b2"); uint256[3] memory c1 = [uint256(1), 2, 3]; uint256[4] memory c2 = [uint256(1), 2, 3, 4]; test = keccak256(abi.encodePacked(c1)) != keccak256(abi.encodePacked(c2)); assertTrue(test, "c1 should not equal c2"); uint256[3] memory d1 = [uint256(1), 2, 3]; uint256[3] memory d2 = [uint256(1), 3, 2]; test = keccak256(abi.encodePacked(d1)) != keccak256(abi.encodePacked(d2)); assertTrue(test, "d1 should not equal d2"); }
6,415,129
./full_match/1/0x79f1A89b5E1168d4de4D3Fa62C7FE1852Fa82c58/sources/contracts/Token.sol
solhint-disable-next-line not-rely-on-time
function addLiquidity() public payable { uint256 _liquidityAmount = balanceOf(address(this)); _approve(address(this), address(_router), _liquidityAmount); address(this), _liquidityAmount, 0, 0, owner(), block.timestamp ); }
17,001,140
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Mintor.sol"; import "./Forest.sol"; import "./Prey.sol"; import "./HunterHound.sol"; contract HunterGame is Mintor, Forest, Ownable { // swtich to turn on/off the game bool _paused = true; // take back staked tokens using rescue() function in rescue mode, rescue mode happens when the code turns buggy bool _rescueEnabled = false; // switch to turn on/off the whitelist bool public _whitelistEnabled = true; // ERC20 contract Prey public prey; // ERC721 contract HunterHound public hunterHound; constructor(address prey_, address hunterHound_) { prey = Prey(prey_); hunterHound = HunterHound(hunterHound_); } /** * return main information of the game */ function getGameStatus() public view returns( bool paused, uint phase, uint minted, uint requested, uint hunterMinted, uint houndMinted, uint hunterStaked, uint houndStaked, uint totalClaimed, uint totalBurned, uint houndsCaptured, uint maxTokensByCurrentPhase ) { paused = _paused; phase = currentPhase(); minted = Mintor.minted; requested = Mintor.requested; hunterMinted = Mintor.hunterMinted; houndMinted = minted - hunterMinted; hunterStaked = Forest.hunterStaked; houndStaked = Forest.houndStaked; totalClaimed = Forest.totalClaimed; totalBurned = Forest.totalBurned; houndsCaptured = Forest.houndsCaptured; maxTokensByCurrentPhase = currentPhaseAmount(); } /** * return phase number of the game by recorded mint requests */ function currentPhase() public view returns(uint p) { uint[4] memory amounts = [PHASE1_AMOUNT,PHASE2_AMOUNT,PHASE3_AMOUNT,PHASE4_AMOUNT]; for (uint i = 0; i < amounts.length; i++) { p += amounts[i]; if (requested < p) { return i+1; } } } /** * get target total number of mints in current phase by recorded mint requests */ function currentPhaseAmount() public view returns(uint p) { uint[4] memory amounts = [PHASE1_AMOUNT,PHASE2_AMOUNT,PHASE3_AMOUNT,PHASE4_AMOUNT]; for (uint256 i = 0; i < amounts.length; i++) { p += amounts[i]; if (requested < p) { return p; } } } /** * check whether the address has enough ETH or $PREY balance to mint in the wallet and validity of the number of mints */ function mintPrecheck(uint amount) private { uint phaseAmount = currentPhaseAmount(); // make sure preciseness of mints in every phase require(amount > 0 && amount <= 50 && (requested % phaseAmount) <= ((requested + amount - 1) % phaseAmount) , "Invalid mint amount"); require(requested + amount <= MAX_TOKENS, "All tokens minted"); uint phase = currentPhase(); if (phase == 1) { require(msg.value == MINT_PRICE * amount, "Invalid payment amount"); } else { require(msg.value == 0, "Only prey"); uint totalMintCost; if (phase == 2) { totalMintCost = MINT_PHASE2_PRICE; } else if (phase == 3) { totalMintCost = MINT_PHASE3_PRICE; } else { totalMintCost = MINT_PHASE4_PRICE; } prey.burn(msg.sender, totalMintCost * amount); } } /************** MINTING **************/ /** * security check and execute `Mintor._request()` function */ function requestMint(uint amount) external payable { require(tx.origin == msg.sender, "No Access"); if (_paused) { require(_whitelistEnabled, 'Paused'); } mintPrecheck(amount); Mintor._request(msg.sender, amount); } /** * security check and execute `Mintor._receive()` function */ function mint() external { require(tx.origin == msg.sender, "No Access"); Mintor._receive(msg.sender, hunterHound); } /** * execute `Mintor._mintRequestState()` function */ function mintRequestState(address requestor) external view returns (uint blockNumber, uint amount, uint state, uint open, uint timeout) { return _mintRequestState(requestor); } /************** Forest **************/ /** * return all holders' stake history */ function stakesByOwner(address owner) external view returns(Stake[] memory) { return stakes[owner]; } /** * security check and execute `Forest._stake()` function */ function stakeToForest(uint256[][] calldata paris) external whenNotPaused { require(tx.origin == msg.sender, "No Access"); Forest._stake(msg.sender, paris, hunterHound); } /** * security check and execute `Forest._claim()` function */ function claimFromForest() external whenNotPaused { require(tx.origin == msg.sender, "No Access"); Forest._claim(msg.sender, prey); } /** * security check and execute `Forest._requestGamble()` function */ function requestGamble(uint action) external whenNotPaused { require(tx.origin == msg.sender, "No Access"); Forest._requestGamble(msg.sender, action); } /** * 执行 `Forest._gambleRequestState()` */ function gambleRequestState(address requestor) external view returns (uint blockNumber, uint action, uint state, uint open, uint timeout) { return Forest._gambleRequestState(requestor); } /** * security check and execute `Forest._unstake()` function */ function unstakeFromForest() external whenNotPaused { require(tx.origin == msg.sender, "No Access"); Forest._unstake(msg.sender, prey, hunterHound); } /** * security check and execute `Forest._rescue()` function */ function rescue() external { require(tx.origin == msg.sender, "No Access"); require(_rescueEnabled, "Rescue disabled"); Forest._rescue(msg.sender, hunterHound); } /************** ADMIN **************/ /** * allows owner to withdraw funds from minting */ function withdraw() external onlyOwner { require(address(this).balance > 0, "No balance available"); payable(owner()).transfer(address(this).balance); } /** * when the game is not paused */ modifier whenNotPaused() { require(_paused == false, "Pausable: paused"); _; } /** * pause/run the game */ function setPaused(bool paused_) external onlyOwner { _paused = paused_; } /** * turn on/off rescue mode */ function setRescueEnabled(bool rescue_) external onlyOwner { _rescueEnabled = rescue_; } /** * turn on/off whitelist */ function setWhitelistEnabled(bool whitelistEnabled_) external onlyOwner { _whitelistEnabled = whitelistEnabled_; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import './Prey.sol'; /** * Useful for simple vesting schedules like "developers get their tokens * after 2 years". */ contract TokenTimelock { // ERC20 basic token contract being held Prey private immutable _token; // beneficiary of tokens after they are released address private immutable _beneficiary; // timestamp when token release is enabled uint256 private immutable _releaseTime; //a vesting duration to release tokens uint256 private immutable _releaseDuration; //record last withdraw time, through which calculate the total withdraw amount uint256 private lastWithdrawTime; //total amount of tokens to release uint256 private immutable _totalToken; constructor( Prey token_, address beneficiary_, uint256 releaseTime_, uint256 releaseDuration_, uint256 totalToken_ ) { require(releaseTime_ > block.timestamp, "TokenTimelock: release time is before current time"); _token = token_; _beneficiary = beneficiary_; _releaseTime = releaseTime_; lastWithdrawTime = _releaseTime; _releaseDuration = releaseDuration_; _totalToken = totalToken_; } /** * @return the token being held. */ function token() public view virtual returns (Prey) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view virtual returns (address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view virtual returns (uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public virtual { require(block.timestamp >= releaseTime(), "TokenTimelock: current time is before release time"); uint256 amount = token().balanceOf(address(this)); uint256 releaseAmount = (block.timestamp - lastWithdrawTime) * _totalToken / _releaseDuration; require(amount >= releaseAmount, "TokenTimelock: no tokens to release"); lastWithdrawTime = block.timestamp; token().transfer(beneficiary(), releaseAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import './TokenTimelock.sol'; /** * $PREY token contract */ contract Prey is ERC20, Ownable { // a mapping from an address to whether or not it can mint / burn mapping(address => bool) public controllers; // the total amount allocated for developers uint constant developerTokenAmount = 600000000 ether; // the total amount allocated for community rewards uint constant communityTokenAmount = 2000000000 ether; // the total amount of tokens staked in the forest to yeild uint constant forestTokenAmount = 2400000000 ether; // the amount of $PREY tokens community has yielded uint mintedByCommunity; // the amount of $PREY tokens staked and yielded in the forest uint mintedByForest; /** * Contract constructor function * @param developerAccount The address that receives locked $PREY rewards for developers, in total 600 million */ constructor(address developerAccount) ERC20("Prey", "PREY") { // create contract to lock $PREY token for 2 years (732 days in total) for developers, after which there is a 10 months(300 days in total) vesting schedule to release 600 million tokens TokenTimelock timelock = new TokenTimelock(this, developerAccount, block.timestamp + 732 days, 300 days, developerTokenAmount); _mint(address(timelock), developerTokenAmount); controllers[_msgSender()] = true; } /** * the function mints $PREY tokens to community members, effectively controls maximum yields * @param account mint $PREY to account * @param amount $PREY amount to mint */ function mintByCommunity(address account, uint256 amount) external { require(controllers[_msgSender()], "Only controllers can mint"); require(mintedByCommunity + amount <= communityTokenAmount, "No mint out"); mintedByCommunity = mintedByCommunity + amount; _mint(account, amount); } /** * the function mints $PREY tokens to community members, effectively controls maximum yields * @param accounts mint $PREY to accounts * @param amount $PREY amount to mint */ function mintsByCommunity(address[] calldata accounts, uint256 amount) external { require(controllers[_msgSender()], "Only controllers can mint"); require(mintedByCommunity + (amount * accounts.length) <= communityTokenAmount, "No mint out"); mintedByCommunity = mintedByCommunity + (amount * accounts.length); for (uint256 i = 0; i < accounts.length; i++) { _mint(accounts[i], amount); } } /** * the function mints $PREY tokens by the forest, effectively controls maximum yields * @param account mint $PREY to account * @param amount $PREY amount to mint */ function mintByForest(address account, uint256 amount) external { require(controllers[_msgSender()], "Only controllers can mint"); require(mintedByForest + amount <= forestTokenAmount, "No mint out"); mintedByForest = mintedByForest + amount; _mint(account, amount); } /** * burn $PREY token by controller * @param account account holds $PREY token * @param amount the amount of $PREY token to burn */ function burn(address account, uint256 amount) external { require(controllers[_msgSender()], "Only controllers can mint"); _burn(account, amount); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import './LotteryBox.sol'; import "./HunterHound.sol"; contract Mintor is LotteryBox { event MintEvent(address indexed operator, uint hunters, uint hounds, uint256[] tokenIds); struct Minting { uint blockNumber; uint amount; } // the cost to mint in every phase uint256 constant MINT_PRICE = .067 ether; uint256 constant MINT_PHASE2_PRICE = 40000 ether; uint256 constant MINT_PHASE3_PRICE = 60000 ether; uint256 constant MINT_PHASE4_PRICE = 80000 ether; // the amount corresponds to every hunter's alpha score uint constant maxAlpha8Count = 500; uint constant maxAlpha7Count = 1500; uint constant maxAlpha6Count = 3000; uint constant maxAlpha5Count = 5000; // 50,000 tokens in total and mint amount in every phase uint constant MAX_TOKENS = 50000; uint constant PHASE1_AMOUNT = 10000; uint constant PHASE2_AMOUNT = 10000; uint constant PHASE3_AMOUNT = 20000; uint constant PHASE4_AMOUNT = 10000; // saves metadataID for next hunter uint private alpha8Count = 1; uint private alpha7Count = 1; uint private alpha6Count = 1; uint private alpha5Count = 1; // saves metadataId for next hound uint internal totalHoundMinted = 1; // saves mint request of users mapping(address => Minting) internal mintRequests; // total minted amount uint256 internal minted; // total minted number of hunters uint256 internal hunterMinted; // recorded mint requests uint internal requested; /** * check mint request * @return blockNumber mint request block * @return amount mint amount * @return state mint state * @return open NFT reavel countdown * @return timeout NFT request reveal timeout countdown */ function _mintRequestState(address requestor) internal view returns (uint blockNumber, uint amount, uint state, uint open, uint timeout) { Minting memory req = mintRequests[requestor]; blockNumber = req.blockNumber; amount = req.amount; state = boxState(req.blockNumber); open = openCountdown(req.blockNumber); timeout = timeoutCountdown(req.blockNumber); } /** * create mint request, record requested block and data */ function _request(address requestor, uint amount) internal { require(mintRequests[requestor].blockNumber == 0, 'Request already exists'); mintRequests[requestor] = Minting({ blockNumber: block.number, amount: amount }); requested = requested + amount; } /** * process mint request to get random number, through which to determine hunter or hound */ function _receive(address requestor, HunterHound hh) internal { Minting memory minting = mintRequests[requestor]; require(minting.blockNumber > 0, "No mint request found"); delete mintRequests[requestor]; uint random = openBox(minting.blockNumber); uint boxResult = percentNumber(random); uint percent = boxResult; uint hunters = 0; uint256[] memory tokenIds = new uint256[](minting.amount); for (uint256 i = 0; i < minting.amount; i++) { HunterHoundTraits memory traits; if (i > 0 && boxResult > 0) { random = simpleRandom(percent); percent = percentNumber(random); } if (percent == 0) { traits = selectHound(); } else if (percent >= 80) { traits = selectHunter(random); } else { traits = selectHound(); } minted = minted + 1; hh.mintByController(requestor, minted, traits); tokenIds[i] = minted; if (traits.isHunter) { hunters ++; } } if (hunters > 0) { hunterMinted = hunterMinted + hunters; } emit MintEvent(requestor, hunters, minting.amount - hunters, tokenIds); } /** * return a hunter, if hunters run out, return a hound * @param random make parameter random a random seed to generate another random number to determine alpha score of a hunter * if number of hunters with corresponding alpha score runs out, it chooses the one with alpha score minus one util it runs out, otherwise it will be a hound * * probabilities of hunters with different alpha score and their numbers: * alpha 8: 5% 500 * alpha 7: 15% 1500 * alpha 6: 30% 3000 * alpha 5: 50% 5000 */ function selectHunter(uint random) private returns(HunterHoundTraits memory hh) { random = simpleRandom(random); uint percent = percentNumber(random); if (percent <= 5 && alpha8Count <= maxAlpha8Count) { hh.alpha = 8; hh.metadataId = alpha8Count; alpha8Count = alpha8Count + 1; } else if (percent <= 20 && alpha7Count <= maxAlpha7Count) { hh.alpha = 7; hh.metadataId = alpha7Count; alpha7Count = alpha7Count + 1; } else if (percent <= 50 && alpha6Count <= maxAlpha6Count) { hh.alpha = 6; hh.metadataId = alpha6Count; alpha6Count = alpha6Count + 1; } else if (alpha5Count <= maxAlpha5Count) { hh.alpha = 5; hh.metadataId = alpha5Count; alpha5Count = alpha5Count + 1; } else { return selectHound(); } hh.isHunter = true; } /** * return a hound */ function selectHound() private returns(HunterHoundTraits memory hh) { hh.isHunter = false; hh.metadataId = totalHoundMinted; totalHoundMinted = totalHoundMinted + 1; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract LotteryBox { // take 3 blocks' hash values to make a random seed uint constant SEED_BLOCK_HASH_AMOUNT = 3; // blackhash can only retrieve the most recent 256 blocks' hash values uint constant MAX_BLOCK_HASH_DISTANCE = 256; /** * generate a simple random number using the parameter */ function simpleRandom(uint seed) internal view returns(uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, block.timestamp, seed ))); } /** * Using the hashes of `SEED_BLOCK_HASH_AMOUNT` previously generated blocks as random seed to generate a random number, based on height of the request block */ function randomNumber(uint requestBlockNumber, uint seed) internal view returns (uint256) { bytes32[SEED_BLOCK_HASH_AMOUNT] memory blockhashs; for (uint i = 0; i < SEED_BLOCK_HASH_AMOUNT; i++) { blockhashs[i] = blockhash(requestBlockNumber+1+i); } return uint256(keccak256(abi.encodePacked( tx.origin, blockhashs, seed ))); } /** * request status */ function boxState(uint requestBlockNumber) internal view returns (uint) { if (requestBlockNumber == 0) { return 0; // not requested } if (openCountdown(requestBlockNumber) > 0) { return 1; // waiting for reveal } if (timeoutCountdown(requestBlockNumber) > 0) { return 2; // waiting to reveal the result } return 3; // timeout } /** * reveal countdown */ function openCountdown(uint requestBlockNumber) internal view returns(uint) { return countdown(requestBlockNumber, SEED_BLOCK_HASH_AMOUNT+1); } /** * timeout countdown */ function timeoutCountdown(uint requestBlockNumber) internal view returns(uint) { return countdown(requestBlockNumber, MAX_BLOCK_HASH_DISTANCE+1); } /** * calculate countdown */ function countdown(uint requestBlockNumber, uint v) internal view returns(uint) { uint diff = block.number - requestBlockNumber; if (diff > v) { return 0; } return v - diff; } /** * convert big random number into less or equal to 100 random number */ function percentNumber(uint random) internal pure returns(uint) { if (random > 0) { return (random % 100) + 1; } return 0; } /** * generate big random number through block height */ function openBox(uint requestBlockNumber) internal view returns (uint) { require(openCountdown(requestBlockNumber) == 0, "Invalid block number"); if (timeoutCountdown(requestBlockNumber) > 0) { return randomNumber(requestBlockNumber, 0); } else { return 0; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; struct HunterHoundTraits { bool isHunter; uint alpha; uint metadataId; } uint constant MIN_ALPHA = 5; uint constant MAX_ALPHA = 8; contract HunterHound is ERC721Enumerable, Ownable { using Strings for uint256; // a mapping from an address to whether or not it can mint / burn mapping(address => bool) public controllers; // save token traits mapping(uint256 => HunterHoundTraits) private tokenTraits; //the base url for metadata string baseUrl = "ipfs://QmZWmcX4jRVZtQGQY64U26wkA83QNB1msZUhjqxJEyfaWP/"; constructor() ERC721("HunterHound","HH") { } /** * set base URL for metadata */ function setBaseUrl(string calldata baseUrl_) external onlyOwner { baseUrl = baseUrl_; } /** * get token traits */ function getTokenTraits(uint256 tokenId) external view returns (HunterHoundTraits memory) { return tokenTraits[tokenId]; } /** * get multiple token traits */ function getTraitsByTokenIds(uint256[] calldata tokenIds) external view returns (HunterHoundTraits[] memory traits) { traits = new HunterHoundTraits[](tokenIds.length); for (uint256 i = 0; i < tokenIds.length; i++) { traits[i] = tokenTraits[tokenIds[i]]; } } /** * Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { HunterHoundTraits memory s = tokenTraits[tokenId]; return string(abi.encodePacked( baseUrl, s.isHunter ? 'Hunter' : 'Hound', '-', s.alpha.toString(), '/', s.isHunter ? 'Hunter' : 'Hound', '-', s.alpha.toString(), '-', s.metadataId.toString(), '.json' )); } /** * return holder's entire tokens */ function tokensByOwner(address owner) external view returns (uint256[] memory tokenIds, HunterHoundTraits[] memory traits) { uint totalCount = balanceOf(owner); tokenIds = new uint256[](totalCount); traits = new HunterHoundTraits[](totalCount); for (uint256 i = 0; i < totalCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); traits[i] = tokenTraits[tokenIds[i]]; } } /** * return token traits */ function isHunterAndAlphaByTokenId(uint256 tokenId) external view returns (bool, uint) { HunterHoundTraits memory traits = tokenTraits[tokenId]; return (traits.isHunter, traits.alpha); } /** * controller to mint a token */ function mintByController(address account, uint256 tokenId, HunterHoundTraits calldata traits) external { require(controllers[_msgSender()], "Only controllers can mint"); tokenTraits[tokenId] = traits; _safeMint(account, tokenId); } /** * controller to transfer a token */ function transferByController(address from, address to, uint256 tokenId) external { require(controllers[_msgSender()], "Only controllers can transfer"); _transfer(from, to, tokenId); } /** * enables an address to mint / burn * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address from minting / burning * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import './LotteryBox.sol'; import './HunterHound.sol'; import './Prey.sol'; contract Forest is LotteryBox { event StakeEvent(address indexed operator, uint256[][] pairs); event ClaimEvent(address indexed operator, uint256 receiveProfit, uint256 totalProfit); event UnstakeEvent(address indexed operator, address indexed recipient, uint256 indexed tokenId, uint256 receiveProfit, uint256 totalProfit); struct Stake{ uint timestamp; bool hunter; uint hounds; uint alpha; uint256[] tokenIds; } uint constant GAMBLE_CLAIM = 1; uint constant GAMBLE_UNSTAKE = 2; uint constant GAMBLE_UNSTAKE_GREDDY = 3; // action 1:claim 2:unstake 3:unstake with greddy struct Gamble { uint action; uint blockNumber; } // the minimum amount of $PREY tokens to own before unstaking uint constant MINIMUN_UNSTAKE_AMOUNT = 20000 ether; // every hound receives 10,000 tokens a day uint constant PROFIT_PER_SINGLE_HOUND = 10000 ether; // the total profit uint constant TOTAL_PROFIT = 2400000000 ether; // the total claimed $PREY including burned in the game uint internal totalClaimed; // the total bunred $PREY uint internal totalBurned; // staked list mapping(address => Stake[]) internal stakes; // record original owner of the token mapping(uint => address) internal tokenOwners; // record tokenId of the hunters who have corresponding alpha score mapping(uint256 => uint256[]) internal hunterAlphaMap; // record index of hunter tokenId in `hunterAlphaMap` mapping(uint256 => uint256) internal hunterTokenIndices; // staked hounds count uint internal houndStaked; // staked hunters count uint internal hunterStaked; // the number of hounds adopted by other hunters uint internal houndsCaptured; mapping(address => Gamble) internal gambleRequests; /** * When there is a gamble request */ modifier whenGambleRequested() { require(gambleRequests[msg.sender].blockNumber == 0, "Unstake or claim first"); _; } /** * stake submitted tokens group and transfer to the staking contract */ function _stake(address owner, uint256[][] calldata pairs, HunterHound hh) internal whenGambleRequested { require(pairs.length > 0, "Tokens empty"); require(totalClaimed < TOTAL_PROFIT, "No profit"); uint totalHunter = 0; uint totalHounds = 0; (totalHunter, totalHounds) = _storeStake(owner, pairs, hh); hunterStaked = hunterStaked + totalHunter; houndStaked = houndStaked + totalHounds; // transfer token for (uint256 i = 0; i < pairs.length; i++) { for (uint256 j = 0; j < pairs[i].length; j++) { uint256 tokenId = pairs[i][j]; hh.transferByController(owner, address(this), tokenId); } } emit StakeEvent(owner, pairs); } /** * store staking groups */ function _storeStake(address owner, uint256[][] calldata paris, HunterHound hh) private returns(uint totalHunter, uint totalHounds) { for (uint256 i = 0; i < paris.length; i++) { uint256[] calldata tokenIds = paris[i]; uint hunters; uint hounds; uint256 hunterAlpha; uint hunterIndex = 0; (hunters, hounds, hunterAlpha, hunterIndex) = _storeTokenOwner(owner, tokenIds, hh); require(hounds > 0 && hounds <= 3, "Must have 1-3 hound in a pair"); require(hunters <= 1, "Only be one hunter in a pair"); // in order to select a hound, a hunter must be placed in the rear of the group require(hunters == 0 || hunterIndex == (tokenIds.length-1), "Hunter must be last one"); totalHunter = totalHunter + hunters; totalHounds = totalHounds + hounds; stakes[owner].push(Stake({ timestamp: block.timestamp, hunter: hunters > 0, hounds: hounds, alpha: hunterAlpha, tokenIds: tokenIds })); if (hunters > 0) { uint256 hunterTokenId = tokenIds[tokenIds.length-1]; hunterTokenIndices[hunterTokenId] = hunterAlphaMap[hunterAlpha].length; hunterAlphaMap[hunterAlpha].push(hunterTokenId); } } } /** * record token owner in order to return $PREY token correctly to the owner in case of unstaking */ function _storeTokenOwner(address owner, uint[] calldata tokenIds, HunterHound hh) private returns(uint hunters,uint hounds,uint hunterAlpha,uint hunterIndex) { for (uint256 j = 0; j < tokenIds.length; j++) { uint256 tokenId = tokenIds[j]; require(tokenOwners[tokenId] == address(0), "Unstake first"); require(hh.ownerOf(tokenId) == owner, "Not your token"); bool isHunter; uint alpha; (isHunter, alpha) = hh.isHunterAndAlphaByTokenId(tokenId); if (isHunter) { hunters = hunters + 1; hunterAlpha = alpha; hunterIndex = j; } else { hounds = hounds + 1; } tokenOwners[tokenId] = owner; } } /** * calculate and claim staked reward, if the players chooses to gamble, there's a probability to lose all rewards */ function _claim(address owner, Prey prey) internal { uint requestBlockNumber = gambleRequests[owner].blockNumber; uint totalProfit = _claimProfit(owner, false); uint receiveProfit; if (requestBlockNumber > 0) { require(gambleRequests[owner].action == GAMBLE_CLAIM, "Unstake first"); uint random = openBox(requestBlockNumber); uint percent = percentNumber(random); if (percent <= 50) { receiveProfit = 0; } else { receiveProfit = totalProfit; } delete gambleRequests[owner]; } else { receiveProfit = (totalProfit * 80) / 100; } if (receiveProfit > 0) { prey.mintByForest(owner, receiveProfit); } if (totalProfit - receiveProfit > 0) { totalBurned = totalBurned + (totalProfit - receiveProfit); } emit ClaimEvent(owner, receiveProfit, totalProfit); } /** * calculate stake rewards, reset timestamp in case of claiming */ function _collectStakeProfit(address owner, bool unstake) private returns (uint profit) { for (uint i = 0; i < stakes[owner].length; i++) { Stake storage stake = stakes[owner][i]; profit = profit + _caculateProfit(stake); if (!unstake) { stake.timestamp = block.timestamp; } } require(unstake == false || profit >= MINIMUN_UNSTAKE_AMOUNT, "Minimum claim is 20000 PREY"); } /** * return claimable staked rewards, update `totalClaimed` */ function _claimProfit(address owner, bool unstake) private returns (uint) { uint profit = _collectStakeProfit(owner, unstake); if (totalClaimed + profit > TOTAL_PROFIT) { profit = TOTAL_PROFIT - totalClaimed; } totalClaimed = totalClaimed + profit; return profit; } /** * create a gamble request in case of unstaking or claim with gambling */ function _requestGamble(address owner, uint action) internal whenGambleRequested { require(stakes[owner].length > 0, 'Stake first'); require(action == GAMBLE_CLAIM || action == GAMBLE_UNSTAKE || action == GAMBLE_UNSTAKE_GREDDY, 'Invalid action'); if (action != GAMBLE_CLAIM) { _collectStakeProfit(owner, true); } gambleRequests[owner] = Gamble({ action: action, blockNumber: block.number }); } /** * return gamble request status */ function _gambleRequestState(address requestor) internal view returns (uint blockNumber, uint action, uint state, uint open, uint timeout) { Gamble memory req = gambleRequests[requestor]; blockNumber = req.blockNumber; action = req.action; state = boxState(req.blockNumber); open = openCountdown(req.blockNumber); timeout = timeoutCountdown(req.blockNumber); } /** * claim all profits and take back staked tokens in case of unstaking * 20% chance to lose one of the hounds and adopted by other hunter * if players chooses to gamble, 50% chance to burn all the profits */ function _unstake(address owner, Prey prey, HunterHound hh) internal { uint requestBlockNumber = gambleRequests[owner].blockNumber; require(requestBlockNumber > 0, "No unstake request found"); uint action = gambleRequests[owner].action; require(action == GAMBLE_UNSTAKE || action == GAMBLE_UNSTAKE_GREDDY, "Claim first"); uint256 totalProfit = _claimProfit(owner, true); uint random = openBox(requestBlockNumber); uint percent = percentNumber(random); address houndRecipient; if (percent <= 20) { //draw a player who has a hunter in case of losing houndRecipient= selectLuckyRecipient(owner, percent); if (houndRecipient != address(0)) { houndsCaptured = houndsCaptured + 1; } } uint receiveProfit = totalProfit; if (action == GAMBLE_UNSTAKE_GREDDY) { // 50/50 chance to lose all or take all if (percent > 0) { random = randomNumber(requestBlockNumber, random); percent = percentNumber(random); if (percent <= 50) { receiveProfit = 0; } } else { receiveProfit = 0; } } else { receiveProfit = (receiveProfit * 80) / 100; } delete gambleRequests[owner]; uint totalHunter = 0; uint totalHound = 0; uint256 capturedTokenId; (totalHunter, totalHound, capturedTokenId) = _cleanOwner(percent, owner, hh, houndRecipient); hunterStaked = hunterStaked - totalHunter; houndStaked = houndStaked - totalHound; delete stakes[owner]; if (receiveProfit > 0) { prey.mintByForest(owner, receiveProfit); } if (totalProfit - receiveProfit > 0) { totalBurned = totalBurned + (totalProfit - receiveProfit); } emit UnstakeEvent(owner, houndRecipient, capturedTokenId, receiveProfit, totalProfit); } /** * delete all data on staking, if `houndRecipient` exists, use `percent` to generate a random number and choose a hound to transfer */ function _cleanOwner(uint percent, address owner, HunterHound hh, address houndRecipient) private returns(uint totalHunter, uint totalHound, uint256 capturedTokenId) { uint randomRow = percent % stakes[owner].length; for (uint256 i = 0; i < stakes[owner].length; i++) { Stake memory stake = stakes[owner][i]; totalHound = totalHound + stake.tokenIds.length; if (stake.hunter) { totalHunter = totalHunter + 1; totalHound = totalHound - 1; uint256 hunterTokenId = stake.tokenIds[stake.tokenIds.length-1]; uint alphaHunterLength = hunterAlphaMap[stake.alpha].length; if (alphaHunterLength > 1 && hunterTokenIndices[hunterTokenId] < (alphaHunterLength-1)) { uint lastHunterTokenId = hunterAlphaMap[stake.alpha][alphaHunterLength - 1]; hunterTokenIndices[lastHunterTokenId] = hunterTokenIndices[hunterTokenId]; hunterAlphaMap[stake.alpha][hunterTokenIndices[hunterTokenId]] = lastHunterTokenId; } hunterAlphaMap[stake.alpha].pop(); delete hunterTokenIndices[hunterTokenId]; } for (uint256 j = 0; j < stake.tokenIds.length; j++) { uint256 tokenId = stake.tokenIds[j]; delete tokenOwners[tokenId]; // randomly select 1 hound if (i == randomRow && houndRecipient != address(0) && (stake.tokenIds.length == 1 || j == (percent % (stake.tokenIds.length-1)))) { hh.transferByController(address(this), houndRecipient, tokenId); capturedTokenId = tokenId; } else { hh.transferByController(address(this), owner, tokenId); } } } } /** * of all hunters staked, choose one to adopt the hound, hunter with higher alpha score takes precedence. * alpha 8: 50% * alpha 7: 30% * alpha 6: 15% * alpha 5: 5% */ function selectLuckyRecipient(address owner, uint seed) private view returns (address) { uint random = simpleRandom(seed); uint percent = percentNumber(random); uint alpha; if (percent <= 5) { alpha = 5; } else if (percent <= 20) { alpha = 6; } else if (percent <= 50) { alpha = 7; } else { alpha = 8; } uint alphaCount = 4; uint startAlpha = alpha; bool directionUp = true; while(alphaCount > 0) { alphaCount --; uint hunterCount = hunterAlphaMap[alpha].length; if (hunterCount != 0) { uint index = random % hunterCount; uint count = 0; while(count < hunterCount) { if (index >= hunterCount) { index = 0; } address hunterOwner = tokenOwners[hunterAlphaMap[alpha][index]]; if (owner != hunterOwner) { return hunterOwner; } index ++; count ++; } } if (alpha >= 8) { directionUp = false; alpha = startAlpha; } if (directionUp) { alpha ++; } else { alpha --; } } return address(0); } /** * calculate the claimable profits of the stake */ function _caculateProfit(Stake memory stake) internal view returns (uint) { uint profitPerStake = 0; if (stake.hunter) { profitPerStake = ((stake.hounds * PROFIT_PER_SINGLE_HOUND) * (stake.alpha + 10)) / 10; } else { profitPerStake = stake.hounds * PROFIT_PER_SINGLE_HOUND; } return (block.timestamp - stake.timestamp) * profitPerStake / 1 days; } /** * take back all staked tokens in case of rescue mode */ function _rescue(address owner, HunterHound hh) internal { delete gambleRequests[owner]; uint totalHound = 0; uint totalHunter = 0; (totalHunter, totalHound, ) = _cleanOwner(0, owner, hh, address(0)); delete stakes[owner]; houndStaked = houndStaked - totalHound; hunterStaked = hunterStaked - totalHunter; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } }
stake submitted tokens group and transfer to the staking contract/ transfer token
function _stake(address owner, uint256[][] calldata pairs, HunterHound hh) internal whenGambleRequested { require(pairs.length > 0, "Tokens empty"); require(totalClaimed < TOTAL_PROFIT, "No profit"); uint totalHunter = 0; uint totalHounds = 0; (totalHunter, totalHounds) = _storeStake(owner, pairs, hh); hunterStaked = hunterStaked + totalHunter; houndStaked = houndStaked + totalHounds; for (uint256 i = 0; i < pairs.length; i++) { for (uint256 j = 0; j < pairs[i].length; j++) { uint256 tokenId = pairs[i][j]; hh.transferByController(owner, address(this), tokenId); } } emit StakeEvent(owner, pairs); }
13,018,159
/** *Submitted for verification at Etherscan.io on 2022-03-17 */ /** *Submitted for verification at Etherscan.io on 2022-03-17 */ /** *Submitted for verification at Etherscan.io on 2022-03-08 */ // SPDX-License-Identifier: MIT // File: contracts/libs/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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/libs/IERC20.sol pragma solidity >=0.4.0; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the erc20 token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/libs/SafeMath.sol pragma solidity ^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) { 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/libs/SafeERC20.sol pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // File: contracts/libs/EnumerableSet.sol pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: contracts/libs/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: contracts/libs/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: contracts/libs/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: contracts/libs/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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/libs/Ownable.sol pragma solidity ^0.8.0; abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: contracts/libs/Pausable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Ownable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function pause() external onlyOwner whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() external onlyOwner whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/libs/ReentrancyGuard.sol pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and 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; } } pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File: contracts/NftStaking.sol pragma solidity ^0.8.0; contract NftStaking is ReentrancyGuard, Pausable, IERC721Receiver { using SafeMath for uint256; using EnumerableSet for EnumerableSet.UintSet; using SafeERC20 for IERC20; address public constant DEAD = 0x000000000000000000000000000000000000dEaD; enum Rarity { COMMON, RARE, ICONIC, GOLDEN } enum StakeType { UNLOCKED, LOCKED, PAIR_LOCKED } bytes32 public SEASON1_MERKLE_ROOT; bytes32 public SEASON2_MERKLE_ROOT; /** Season1 / Season2 NFT address */ address public _season1Nft; address public _season2Nft; /** Reward Token address */ address public _rewardToken; // Withdraw lock period uint256 public _lockPeriod = 60 days; // Lock period 60 days uint16 public _unstakeFee = 500; // Unstake fee 5% uint16 public _forcedUnstakeFee = 10000; // Force unstake fee 100% struct NftStakeInfo { Rarity _rarity; bool _isLocked; uint256 _pairedTokenId; uint256 _stakedAt; } struct UserInfo { EnumerableSet.UintSet _season1Nfts; EnumerableSet.UintSet _season2Nfts; mapping(uint256 => NftStakeInfo) _season1StakeInfos; mapping(uint256 => NftStakeInfo) _season2StakeInfos; uint256 _pending; // Not claimed uint256 _totalClaimed; // Claimed so far uint256 _lastClaimedAt; uint256 _pairCount; // Paired count } mapping(Rarity => uint256) _season1BaseRpds; // RPD: reward per day mapping(Rarity => uint16) _season1LockedExtras; mapping(Rarity => mapping(StakeType => uint16)) _season2Extras; // Info of each user that stakes LP tokens. mapping(address => UserInfo) private _userInfo; event Staked( address indexed account, uint256 tokenId, bool isSeason1, bool isLocked ); event Unstaked(address indexed account, uint256 tokenId, bool isSeason1); event Locked(address indexed account, uint256 tokenId, bool isSeason1); event Paired( address indexed account, uint256 season1TokenId, uint256 season2TokenId ); event Harvested(address indexed account, uint256 amount); event InsufficientRewardToken( address indexed account, uint256 amountNeeded, uint256 balance ); constructor(address __rewardToken, address __season1Nft) { IERC20(__rewardToken).balanceOf(address(this)); IERC721(__season1Nft).balanceOf(address(this)); _rewardToken = __rewardToken; _season1Nft = __season1Nft; // Base reward per day _season1BaseRpds[Rarity.COMMON] = 50 ether; _season1BaseRpds[Rarity.RARE] = 125 ether; _season1BaseRpds[Rarity.ICONIC] = 250 ether; // Season1 locked cases extra percentage _season1LockedExtras[Rarity.COMMON] = 2000; // 20% _season1LockedExtras[Rarity.COMMON] = 2000; // 20% _season1LockedExtras[Rarity.COMMON] = 2000; // 20% // Season2 extra percentage _season2Extras[Rarity.COMMON][StakeType.UNLOCKED] = 1000; _season2Extras[Rarity.COMMON][StakeType.LOCKED] = 2000; _season2Extras[Rarity.COMMON][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.RARE][StakeType.UNLOCKED] = 2000; _season2Extras[Rarity.RARE][StakeType.LOCKED] = 2000; _season2Extras[Rarity.RARE][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.ICONIC][StakeType.UNLOCKED] = 3500; _season2Extras[Rarity.ICONIC][StakeType.LOCKED] = 2000; _season2Extras[Rarity.ICONIC][StakeType.PAIR_LOCKED] = 5000; _season2Extras[Rarity.GOLDEN][StakeType.UNLOCKED] = 5000; _season2Extras[Rarity.GOLDEN][StakeType.LOCKED] = 2000; _season2Extras[Rarity.GOLDEN][StakeType.PAIR_LOCKED] = 5000; } function setSeason2Nft(address __season2Nft) external onlyOwner { IERC721(__season2Nft).balanceOf(address(this)); _season2Nft = __season2Nft; } function getRewardInNormal( uint256 __rpd, uint256 __stakedAt, uint256 __lastClaimedAt ) private view returns (uint256) { uint256 timePassed = __stakedAt > __lastClaimedAt ? block.timestamp.sub(__stakedAt) : block.timestamp.sub(__lastClaimedAt); return __rpd.mul(timePassed).div(1 days); } function getRewardInLocked( uint256 __rpd, uint256 __extraRate, uint256 __stakedAt, uint256 __lastClaimedAt ) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { uint256 lockEndAt = __stakedAt.add(_lockPeriod); if (lockEndAt > block.timestamp) { lockedAmount = __rpd .mul(block.timestamp.sub(__stakedAt)) .mul(uint256(10000).add(__extraRate)) .div(10000) .div(1 days); } else { uint256 timePassed = __lastClaimedAt >= lockEndAt ? block.timestamp.sub(__lastClaimedAt) : block.timestamp.sub(__stakedAt); unlockedAmount = __rpd .mul(timePassed) .mul(uint256(10000).add(__extraRate)) .div(10000) .div(1 days); } } function getSeason1Rewards(address __account, uint256 __nftId) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { UserInfo storage user = _userInfo[__account]; NftStakeInfo storage season1StakeInfo = user._season1StakeInfos[ __nftId ]; Rarity season1Rarity = season1StakeInfo._rarity; uint256 baseRpd = _season1BaseRpds[season1Rarity]; // For the locked staking add extra percentage if (season1StakeInfo._isLocked) { (lockedAmount, unlockedAmount) = getRewardInLocked( baseRpd, _season1LockedExtras[season1Rarity], season1StakeInfo._stakedAt, user._lastClaimedAt ); } else { unlockedAmount = getRewardInNormal( baseRpd, season1StakeInfo._stakedAt, user._lastClaimedAt ); } } function getPairedSeason2Rewards(address __account, uint256 __nftId) private view returns (uint256 lockedAmount, uint256 unlockedAmount) { UserInfo storage user = _userInfo[__account]; NftStakeInfo storage season1StakeInfo = user._season1StakeInfos[ __nftId ]; NftStakeInfo storage season2StakeInfo = user._season2StakeInfos[ season1StakeInfo._pairedTokenId ]; Rarity season1Rarity = season1StakeInfo._rarity; Rarity season2Rarity = season2StakeInfo._rarity; uint256 baseRpd = _season1BaseRpds[season1Rarity]; if (season1StakeInfo._pairedTokenId == 0) { lockedAmount = 0; unlockedAmount = 0; } else if (season2StakeInfo._isLocked) { // extra rate is wheter season1 is locked or not uint256 rpdExtraRate = season1StakeInfo._isLocked ? _season2Extras[season2Rarity][StakeType.PAIR_LOCKED] : _season2Extras[season2Rarity][StakeType.LOCKED]; (lockedAmount, unlockedAmount) = getRewardInLocked( baseRpd, rpdExtraRate, season2StakeInfo._stakedAt, user._lastClaimedAt ); } else { // base rpd for the season2 unlocked baseRpd = baseRpd .mul(_season2Extras[season2Rarity][StakeType.UNLOCKED]) .div(10000); unlockedAmount = getRewardInNormal( baseRpd, season2StakeInfo._stakedAt, user._lastClaimedAt ); } } function viewProfit(address __account) public view returns ( uint256 totalEarned, uint256 totalClaimed, uint256 lockedRewards, uint256 unlockedRewards ) { UserInfo storage user = _userInfo[__account]; totalClaimed = user._totalClaimed; unlockedRewards = user._pending; uint256 countSeason1Nfts = user._season1Nfts.length(); uint256 index; for (index = 0; index < countSeason1Nfts; index++) { uint256 pendingLockedRewards = 0; uint256 pendingUnlockedRewards = 0; (pendingLockedRewards, pendingUnlockedRewards) = getSeason1Rewards( __account, user._season1Nfts.at(index) ); // Add season1 reward if (pendingLockedRewards > 0) { lockedRewards = lockedRewards.add(pendingLockedRewards); } if (pendingUnlockedRewards > 0) { unlockedRewards = unlockedRewards.add(pendingUnlockedRewards); } ( pendingLockedRewards, pendingUnlockedRewards ) = getPairedSeason2Rewards(__account, user._season1Nfts.at(index)); // Add season2 reward if (pendingLockedRewards > 0) { lockedRewards = lockedRewards.add(pendingLockedRewards); } if (pendingUnlockedRewards > 0) { unlockedRewards = unlockedRewards.add(pendingUnlockedRewards); } } totalEarned = totalClaimed.add(lockedRewards).add(unlockedRewards); } /** * @notice Get season1 nfts */ function viewSeason1Nfts(address __account) external view returns (uint256[] memory season1Nfts, bool[] memory lockStats) { UserInfo storage user = _userInfo[__account]; uint256 countSeason1Nfts = user._season1Nfts.length(); season1Nfts = new uint256[](countSeason1Nfts); lockStats = new bool[](countSeason1Nfts); uint256 index; uint256 tokenId; for (index = 0; index < countSeason1Nfts; index++) { tokenId = user._season1Nfts.at(index); season1Nfts[index] = tokenId; lockStats[index] = user._season1StakeInfos[tokenId]._isLocked; } } /** * @notice Get season2 nfts */ function viewSeason2Nfts(address __account) external view returns (uint256[] memory season2Nfts, bool[] memory lockStats) { UserInfo storage user = _userInfo[__account]; uint256 countSeason2Nfts = user._season2Nfts.length(); season2Nfts = new uint256[](countSeason2Nfts); lockStats = new bool[](countSeason2Nfts); uint256 index; uint256 tokenId; for (index = 0; index < countSeason2Nfts; index++) { tokenId = user._season2Nfts.at(index); season2Nfts[index] = tokenId; lockStats[index] = user._season2StakeInfos[tokenId]._isLocked; } } /** * @notice Get paired season1 / season2 nfts */ function viewPairedNfts(address __account) external view returns ( uint256[] memory pairedSeason1Nfts, uint256[] memory pairedSeason2Nfts ) { UserInfo storage user = _userInfo[__account]; uint256 pairCount = user._pairCount; pairedSeason1Nfts = new uint256[](pairCount); pairedSeason2Nfts = new uint256[](pairCount); uint256 index; uint256 tokenId; uint256 rindex = 0; uint256 season2NftCount = user._season2Nfts.length(); for (index = 0; index < season2NftCount; index++) { tokenId = user._season2Nfts.at(index); if (user._season2StakeInfos[tokenId]._pairedTokenId == 0) { continue; } pairedSeason1Nfts[rindex] = user ._season2StakeInfos[tokenId] ._pairedTokenId; pairedSeason2Nfts[rindex] = tokenId; rindex = rindex.add(1); } } // Verify that a given leaf is in the tree. function isWhiteListedSeason1(bytes32 _leafNode, bytes32[] memory _proof) public view returns (bool) { return MerkleProof.verify(_proof, SEASON1_MERKLE_ROOT, _leafNode); } function isWhiteListedSeason2(bytes32 _leafNode, bytes32[] memory _proof) public view returns (bool) { return MerkleProof.verify(_proof, SEASON2_MERKLE_ROOT, _leafNode); } // Generate the leaf node (just the hash of tokenID concatenated with the account address) function toLeaf( uint256 tokenID, uint256 index, uint256 amount ) public pure returns (bytes32) { return keccak256(abi.encodePacked(index, tokenID, amount)); } function setMerkleRoot(bytes32 _season1Root, bytes32 _season2Root) external onlyOwner { SEASON1_MERKLE_ROOT = _season1Root; SEASON2_MERKLE_ROOT = _season2Root; } function updateFeeValues(uint16 __unstakeFee, uint16 __forcedUnstakeFee) external onlyOwner { _unstakeFee = __unstakeFee; _forcedUnstakeFee = __forcedUnstakeFee; } function updateLockPeriod(uint256 __lockPeriod) external onlyOwner { require(__lockPeriod > 0, "Invalid lock period"); _lockPeriod = __lockPeriod; } function updateSeason1BaseRpd(Rarity __rarity, uint256 __rpd) external onlyOwner { require(__rpd > 0, "Non zero values required"); _season1BaseRpds[__rarity] = __rpd; } function updateSeason1LockedExtraPercent( Rarity __rarity, uint16 __lockedExtraPercent ) external onlyOwner { _season1LockedExtras[__rarity] = __lockedExtraPercent; } function updateSeason2ExtraPercent( Rarity __rarity, StakeType __stakeType, uint16 __extraPercent ) external onlyOwner { _season2Extras[__rarity][__stakeType] = __extraPercent; } function isStaked(address __account, uint256 __tokenId) external view returns (bool) { UserInfo storage user = _userInfo[__account]; return user._season1Nfts.contains(__tokenId) || user._season2Nfts.contains(__tokenId); } /** * @notice Claim rewards */ function claimRewards() external { UserInfo storage user = _userInfo[_msgSender()]; (, , , uint256 unlockedRewards) = viewProfit(_msgSender()); if (unlockedRewards > 0) { uint256 feeAmount = unlockedRewards.mul(_unstakeFee).div(10000); if (feeAmount > 0) { IERC20(_rewardToken).safeTransfer(DEAD, feeAmount); unlockedRewards = unlockedRewards.sub(feeAmount); } if (unlockedRewards > 0) { user._totalClaimed = user._totalClaimed.add(unlockedRewards); IERC20(_rewardToken).safeTransfer(_msgSender(), unlockedRewards); } } user._lastClaimedAt = block.timestamp; } /** * @notice Stake season1 nft */ function stakeSeason1( bool __lockedStaking, uint256[] calldata __tokenIDList, uint256[] calldata __indexList, uint256[] calldata __rarityList, bytes32[][] calldata __proofList ) external nonReentrant whenNotPaused { require( IERC721(_season1Nft).isApprovedForAll(_msgSender(), address(this)), "Not approve nft to staker address" ); UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( isWhiteListedSeason1( toLeaf(__tokenIDList[i], __indexList[i], __rarityList[i]), __proofList[i] ), "Invalid params" ); IERC721(_season1Nft).safeTransferFrom( _msgSender(), address(this), __tokenIDList[i] ); user._season1Nfts.add(__tokenIDList[i]); user._season1StakeInfos[__tokenIDList[i]] = NftStakeInfo({ _rarity: Rarity(__rarityList[i]), _isLocked: __lockedStaking, _stakedAt: block.timestamp, _pairedTokenId: 0 }); emit Staked(_msgSender(), __tokenIDList[i], true, __lockedStaking); } } /** * @notice Stake season2 nft */ function stakeSeason2( bool __lockedStaking, uint256[] calldata __tokenIDList, uint256[] calldata __indexList, uint256[] calldata __rarityList, bytes32[][] calldata __proofList ) external nonReentrant whenNotPaused { require( IERC721(_season2Nft).isApprovedForAll(_msgSender(), address(this)), "Not approve nft to staker address" ); UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( isWhiteListedSeason2( toLeaf(__tokenIDList[i], __indexList[i], __rarityList[i]), __proofList[i] ), "Invalid params" ); IERC721(_season2Nft).safeTransferFrom( _msgSender(), address(this), __tokenIDList[i] ); user._season2Nfts.add(__tokenIDList[i]); user._season2StakeInfos[__tokenIDList[i]] = NftStakeInfo({ _rarity: Rarity(__rarityList[i]), _isLocked: __lockedStaking, _stakedAt: block.timestamp, _pairedTokenId: 0 }); emit Staked(_msgSender(), __tokenIDList[i], false, __lockedStaking); } } function unstakeSeason1(uint256[] calldata __tokenIDList) external nonReentrant { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { require( user._season1Nfts.contains(__tokenIDList[i]), "Not staked one of nfts" ); IERC721(_season1Nft).safeTransferFrom( address(this), _msgSender(), __tokenIDList[i] ); // locked rewards are sent to rewards back to the pool // unlocked rewards are added to the user rewards (, uint256 unlockedRewards) = getSeason1Rewards( _msgSender(), __tokenIDList[i] ); user._pending = user._pending.add(unlockedRewards); user._season1Nfts.remove(__tokenIDList[i]); // If it was paired with a season2 nft, unpair them uint256 pairedTokenId = user ._season1StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { user._season2StakeInfos[pairedTokenId]._pairedTokenId = 0; user._pairCount = user._pairCount.sub(1); } delete user._season1StakeInfos[__tokenIDList[i]]; emit Unstaked(_msgSender(), __tokenIDList[i], true); } } function unstakeSeason2(uint256[] calldata __tokenIDList) external nonReentrant { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { require( user._season2Nfts.contains(__tokenIDList[i]), "Not staked one of nfts" ); IERC721(_season2Nft).safeTransferFrom( address(this), _msgSender(), __tokenIDList[i] ); // If it was paired with a season1 nft, unpair them uint256 pairedTokenId = user ._season2StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { // locked rewards are sent to rewards back to the pool // unlocked rewards are added to the user rewards (, uint256 unlockedRewards) = getPairedSeason2Rewards( _msgSender(), pairedTokenId ); user._pending = user._pending.add(unlockedRewards); } user._season2Nfts.remove(__tokenIDList[i]); if (pairedTokenId > 0) { user._season1StakeInfos[pairedTokenId]._pairedTokenId = 0; user._pairCount = user._pairCount.sub(1); } delete user._season2StakeInfos[__tokenIDList[i]]; emit Unstaked(_msgSender(), __tokenIDList[i], false); } } /** * @notice Lock season1 nft from the unlocked pool to the lock pool */ function lockSeason1Nfts(uint256[] calldata __tokenIDList) external onlyOwner { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( user._season1Nfts.contains(__tokenIDList[i]), "One of nfts not staked yet" ); require( !user._season1StakeInfos[__tokenIDList[i]]._isLocked, "Locked already" ); (, uint256 unlockedRewards) = getSeason1Rewards( _msgSender(), __tokenIDList[i] ); user._pending = user._pending.add(unlockedRewards); user._season1StakeInfos[__tokenIDList[i]]._isLocked = true; user._season1StakeInfos[__tokenIDList[i]]._stakedAt = block .timestamp; emit Locked(_msgSender(), __tokenIDList[i], true); } } /** * @notice Lock season2 nft from the unlocked pool to the lock pool */ function lockSeason2Nfts(uint256[] calldata __tokenIDList) external onlyOwner { UserInfo storage user = _userInfo[_msgSender()]; for (uint256 i = 0; i < __tokenIDList.length; i++) { // Check if the params are correct require( user._season2Nfts.contains(__tokenIDList[i]), "One of nfts not staked yet" ); require( !user._season2StakeInfos[__tokenIDList[i]]._isLocked, "Locked already" ); uint256 pairedTokenId = user ._season2StakeInfos[__tokenIDList[i]] ._pairedTokenId; if (pairedTokenId > 0) { (, uint256 unlockedRewards) = getPairedSeason2Rewards( _msgSender(), pairedTokenId ); user._pending = user._pending.add(unlockedRewards); } user._season2StakeInfos[__tokenIDList[i]]._isLocked = true; user._season2StakeInfos[__tokenIDList[i]]._stakedAt = block .timestamp; emit Locked(_msgSender(), __tokenIDList[i], false); } } /** * @notice */ function pairNfts(uint256 __season1TokenID, uint256 __season2TokenID) external nonReentrant whenNotPaused { UserInfo storage user = _userInfo[_msgSender()]; require( user._season1Nfts.contains(__season1TokenID) && user._season2Nfts.contains(__season2TokenID), "One of nfts is not staked" ); require( user._season1StakeInfos[__season1TokenID]._pairedTokenId == 0 && user._season2StakeInfos[__season2TokenID]._pairedTokenId == 0, "Already paired" ); user ._season1StakeInfos[__season1TokenID] ._pairedTokenId = __season2TokenID; user ._season2StakeInfos[__season2TokenID] ._pairedTokenId = __season1TokenID; user._season2StakeInfos[__season2TokenID]._stakedAt = block.timestamp; user._pairCount = user._pairCount.add(1); emit Paired(_msgSender(), __season1TokenID, __season2TokenID); } function safeRewardTransfer(address __to, uint256 __amount) internal returns (uint256) { uint256 balance = IERC20(_rewardToken).balanceOf(address(this)); if (balance >= __amount) { IERC20(_rewardToken).safeTransfer(__to, __amount); return __amount; } if (balance > 0) { IERC20(_rewardToken).safeTransfer(__to, balance); } emit InsufficientRewardToken(__to, __amount, balance); return balance; } function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
Get paired season1 / season2 nfts/
function viewPairedNfts(address __account) external view returns ( uint256[] memory pairedSeason1Nfts, uint256[] memory pairedSeason2Nfts ) { UserInfo storage user = _userInfo[__account]; uint256 pairCount = user._pairCount; pairedSeason1Nfts = new uint256[](pairCount); pairedSeason2Nfts = new uint256[](pairCount); uint256 index; uint256 tokenId; uint256 rindex = 0; uint256 season2NftCount = user._season2Nfts.length(); for (index = 0; index < season2NftCount; index++) { tokenId = user._season2Nfts.at(index); if (user._season2StakeInfos[tokenId]._pairedTokenId == 0) { continue; } pairedSeason1Nfts[rindex] = user ._season2StakeInfos[tokenId] ._pairedTokenId; pairedSeason2Nfts[rindex] = tokenId; rindex = rindex.add(1); } }
6,499,354
./partial_match/1/0x93A20D8EbA6997ABB53aE94bd01727C8e74c8734/sources/TokenCore.sol
has role privilege low level access to role privilege ignores ALL_PRIVILEGES role/
function rolePrivilege(bytes32 _role, bytes4 _privilege) public view returns (bool) { return roles[_role].privileges[_privilege]; }
3,566,147
pragma solidity ^0.4.22; // File: contracts/ERC223/ERC223_receiving_contract.sol /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/ERC223/ERC223.sol /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223 is StandardToken { event Transfer(address indexed from, address indexed to, uint value, bytes data); /** * @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, uint _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data Optional metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); } return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public returns (bool) { bytes memory empty; return transferFrom(_from, _to, _value, empty); } /** * @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 uint the amount of tokens to be transferred * @param _data Optional metadata. */ function transferFrom(address _from, address _to, uint _value, bytes _data) public returns (bool) { super.transferFrom(_from, _to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, _data); } Transfer(_from, _to, _value, _data); return true; } function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; function CappedToken(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } // File: contracts/RootsToken.sol contract RootsToken is CappedToken, ERC223 { string constant public name = "ROOTS Token"; string constant public symbol = "ROOTS"; uint constant public decimals = 18; function RootsToken() public CappedToken(1e10 * 1e18) {} function mintlist(address[] _to, uint256[] _amount) onlyOwner canMint public { require(_to.length == _amount.length); for (uint256 i = 0; i < _to.length; i++) { mint(_to[i], _amount[i]); } } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred. _data Optional metadata./
function transfer(address _to, uint _value, bytes _data) public returns (bool) { super.transfer(_to, _value); if (isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); } return true; }
393,669
pragma solidity ^0.4.24; contract CrabData { modifier crabDataLength(uint256[] memory _crabData) { require(_crabData.length == 8); _; } struct CrabPartData { uint256 hp; uint256 dps; uint256 blockRate; uint256 resistanceBonus; uint256 hpBonus; uint256 dpsBonus; uint256 blockBonus; uint256 mutiplierBonus; } function arrayToCrabPartData( uint256[] _partData ) internal pure crabDataLength(_partData) returns (CrabPartData memory _parsedData) { _parsedData = CrabPartData( _partData[0], // hp _partData[1], // dps _partData[2], // block rate _partData[3], // resistance bonus _partData[4], // hp bonus _partData[5], // dps bonus _partData[6], // block bonus _partData[7]); // multiplier bonus } function crabPartDataToArray(CrabPartData _crabPartData) internal pure returns (uint256[] memory _resultData) { _resultData = new uint256[](8); _resultData[0] = _crabPartData.hp; _resultData[1] = _crabPartData.dps; _resultData[2] = _crabPartData.blockRate; _resultData[3] = _crabPartData.resistanceBonus; _resultData[4] = _crabPartData.hpBonus; _resultData[5] = _crabPartData.dpsBonus; _resultData[6] = _crabPartData.blockBonus; _resultData[7] = _crabPartData.mutiplierBonus; } } contract GeneSurgeon { //0 - filler, 1 - body, 2 - leg, 3 - left claw, 4 - right claw uint256[] internal crabPartMultiplier = [0, 10**9, 10**6, 10**3, 1]; function extractElementsFromGene(uint256 _gene) internal view returns (uint256[] memory _elements) { _elements = new uint256[](4); _elements[0] = _gene / crabPartMultiplier[1] / 100 % 10; _elements[1] = _gene / crabPartMultiplier[2] / 100 % 10; _elements[2] = _gene / crabPartMultiplier[3] / 100 % 10; _elements[3] = _gene / crabPartMultiplier[4] / 100 % 10; } function extractPartsFromGene(uint256 _gene) internal view returns (uint256[] memory _parts) { _parts = new uint256[](4); _parts[0] = _gene / crabPartMultiplier[1] % 100; _parts[1] = _gene / crabPartMultiplier[2] % 100; _parts[2] = _gene / crabPartMultiplier[3] % 100; _parts[3] = _gene / crabPartMultiplier[4] % 100; } } interface GenesisCrabInterface { function generateCrabGene(bool isPresale, bool hasLegendaryPart) external returns (uint256 _gene, uint256 _skin, uint256 _heartValue, uint256 _growthValue); function mutateCrabPart(uint256 _part, uint256 _existingPartGene, uint256 _legendaryPercentage) external returns (uint256); function generateCrabHeart() external view returns (uint256, uint256); } contract LevelCalculator { event LevelUp(address indexed tokenOwner, uint256 indexed tokenId, uint256 currentLevel, uint256 currentExp); event ExpGained(address indexed tokenOwner, uint256 indexed tokenId, uint256 currentLevel, uint256 currentExp); function expRequiredToReachLevel(uint256 _level) internal pure returns (uint256 _exp) { require(_level > 1); uint256 _expRequirement = 10; for(uint256 i = 2 ; i < _level ; i++) { _expRequirement += 12; } _exp = _expRequirement; } } contract Randomable { // Generates a random number base on last block hash function _generateRandom(bytes32 seed) view internal returns (bytes32) { return keccak256(abi.encodePacked(blockhash(block.number-1), seed)); } function _generateRandomNumber(bytes32 seed, uint256 max) view internal returns (uint256) { return uint256(_generateRandom(seed)) % max; } } contract CryptantCrabStoreInterface { function createAddress(bytes32 key, address value) external returns (bool); function createAddresses(bytes32[] keys, address[] values) external returns (bool); function updateAddress(bytes32 key, address value) external returns (bool); function updateAddresses(bytes32[] keys, address[] values) external returns (bool); function removeAddress(bytes32 key) external returns (bool); function removeAddresses(bytes32[] keys) external returns (bool); function readAddress(bytes32 key) external view returns (address); function readAddresses(bytes32[] keys) external view returns (address[]); // Bool related functions function createBool(bytes32 key, bool value) external returns (bool); function createBools(bytes32[] keys, bool[] values) external returns (bool); function updateBool(bytes32 key, bool value) external returns (bool); function updateBools(bytes32[] keys, bool[] values) external returns (bool); function removeBool(bytes32 key) external returns (bool); function removeBools(bytes32[] keys) external returns (bool); function readBool(bytes32 key) external view returns (bool); function readBools(bytes32[] keys) external view returns (bool[]); // Bytes32 related functions function createBytes32(bytes32 key, bytes32 value) external returns (bool); function createBytes32s(bytes32[] keys, bytes32[] values) external returns (bool); function updateBytes32(bytes32 key, bytes32 value) external returns (bool); function updateBytes32s(bytes32[] keys, bytes32[] values) external returns (bool); function removeBytes32(bytes32 key) external returns (bool); function removeBytes32s(bytes32[] keys) external returns (bool); function readBytes32(bytes32 key) external view returns (bytes32); function readBytes32s(bytes32[] keys) external view returns (bytes32[]); // uint256 related functions function createUint256(bytes32 key, uint256 value) external returns (bool); function createUint256s(bytes32[] keys, uint256[] values) external returns (bool); function updateUint256(bytes32 key, uint256 value) external returns (bool); function updateUint256s(bytes32[] keys, uint256[] values) external returns (bool); function removeUint256(bytes32 key) external returns (bool); function removeUint256s(bytes32[] keys) external returns (bool); function readUint256(bytes32 key) external view returns (uint256); function readUint256s(bytes32[] keys) external view returns (uint256[]); // int256 related functions function createInt256(bytes32 key, int256 value) external returns (bool); function createInt256s(bytes32[] keys, int256[] values) external returns (bool); function updateInt256(bytes32 key, int256 value) external returns (bool); function updateInt256s(bytes32[] keys, int256[] values) external returns (bool); function removeInt256(bytes32 key) external returns (bool); function removeInt256s(bytes32[] keys) external returns (bool); function readInt256(bytes32 key) external view returns (int256); function readInt256s(bytes32[] keys) external view returns (int256[]); // internal functions function parseKey(bytes32 key) internal pure returns (bytes32); function parseKeys(bytes32[] _keys) internal pure returns (bytes32[]); } contract StoreRBAC { // stores: storeName -> key -> addr -> isAllowed mapping(uint256 => mapping (uint256 => mapping(address => bool))) private stores; // store names uint256 public constant STORE_RBAC = 1; uint256 public constant STORE_FUNCTIONS = 2; uint256 public constant STORE_KEYS = 3; // rbac roles uint256 public constant RBAC_ROLE_ADMIN = 1; // "admin" // events event RoleAdded(uint256 storeName, address addr, uint256 role); event RoleRemoved(uint256 storeName, address addr, uint256 role); constructor() public { addRole(STORE_RBAC, msg.sender, RBAC_ROLE_ADMIN); } function hasRole(uint256 storeName, address addr, uint256 role) public view returns (bool) { return stores[storeName][role][addr]; } function checkRole(uint256 storeName, address addr, uint256 role) public view { require(hasRole(storeName, addr, role)); } function addRole(uint256 storeName, address addr, uint256 role) internal { stores[storeName][role][addr] = true; emit RoleAdded(storeName, addr, role); } function removeRole(uint256 storeName, address addr, uint256 role) internal { stores[storeName][role][addr] = false; emit RoleRemoved(storeName, addr, role); } function adminAddRole(uint256 storeName, address addr, uint256 role) onlyAdmin public { addRole(storeName, addr, role); } function adminRemoveRole(uint256 storeName, address addr, uint256 role) onlyAdmin public { removeRole(storeName, addr, role); } modifier onlyRole(uint256 storeName, uint256 role) { checkRole(storeName, msg.sender, role); _; } modifier onlyAdmin() { checkRole(STORE_RBAC, msg.sender, RBAC_ROLE_ADMIN); _; } } contract FunctionProtection is StoreRBAC { // standard roles uint256 constant public FN_ROLE_CREATE = 2; // create uint256 constant public FN_ROLE_UPDATE = 3; // update uint256 constant public FN_ROLE_REMOVE = 4; // remove function canCreate() internal view returns (bool) { return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_CREATE); } function canUpdate() internal view returns (bool) { return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_UPDATE); } function canRemove() internal view returns (bool) { return hasRole(STORE_FUNCTIONS, msg.sender, FN_ROLE_REMOVE); } // external functions function applyAllPermission(address _address) external onlyAdmin { addRole(STORE_FUNCTIONS, _address, FN_ROLE_CREATE); addRole(STORE_FUNCTIONS, _address, FN_ROLE_UPDATE); addRole(STORE_FUNCTIONS, _address, FN_ROLE_REMOVE); } } contract CryptantCrabMarketStore is FunctionProtection { // Structure of each traded record struct TradeRecord { uint256 tokenId; uint256 auctionId; uint256 price; uint48 time; address owner; address seller; } // Structure of each trading item struct AuctionItem { uint256 tokenId; uint256 basePrice; address seller; uint48 startTime; uint48 endTime; uint8 state; // 0 - on going, 1 - cancelled, 2 - claimed uint256[] bidIndexes; // storing bidId } struct Bid { uint256 auctionId; uint256 price; uint48 time; address bidder; } // Structure to store withdrawal information struct WithdrawalRecord { uint256 auctionId; uint256 value; uint48 time; uint48 callTime; bool hasWithdrawn; } // stores awaiting withdrawal information mapping(address => WithdrawalRecord[]) public withdrawalList; // stores last withdrawal index mapping(address => uint256) public lastWithdrawnIndex; // All traded records will be stored here TradeRecord[] public tradeRecords; // All auctioned items will be stored here AuctionItem[] public auctionItems; Bid[] public bidHistory; event TradeRecordAdded(address indexed seller, address indexed buyer, uint256 tradeId, uint256 price, uint256 tokenId, uint256 indexed auctionId); event AuctionItemAdded(address indexed seller, uint256 auctionId, uint256 basePrice, uint256 duration, uint256 tokenId); event AuctionBid(address indexed bidder, address indexed previousBidder, uint256 auctionId, uint256 bidPrice, uint256 bidIndex, uint256 tokenId, uint256 endTime); event PendingWithdrawalCleared(address indexed withdrawer, uint256 withdrawnAmount); constructor() public { // auctionItems index 0 should be dummy, // because TradeRecord might not have auctionId auctionItems.push(AuctionItem(0, 0, address(0), 0, 0, 0, new uint256[](1))); // tradeRecords index 0 will be dummy // just to follow the standards skipping the index 0 tradeRecords.push(TradeRecord(0, 0, 0, 0, address(0), address(0))); // bidHistory index 0 will be dummy // just to follow the standards skipping the index 0 bidHistory.push(Bid(0, 0, uint48(0), address(0))); } // external functions // getters function getWithdrawalList(address withdrawer) external view returns ( uint256[] memory _auctionIds, uint256[] memory _values, uint256[] memory _times, uint256[] memory _callTimes, bool[] memory _hasWithdrawn ) { WithdrawalRecord[] storage withdrawalRecords = withdrawalList[withdrawer]; _auctionIds = new uint256[](withdrawalRecords.length); _values = new uint256[](withdrawalRecords.length); _times = new uint256[](withdrawalRecords.length); _callTimes = new uint256[](withdrawalRecords.length); _hasWithdrawn = new bool[](withdrawalRecords.length); for(uint256 i = 0 ; i < withdrawalRecords.length ; i++) { WithdrawalRecord storage withdrawalRecord = withdrawalRecords[i]; _auctionIds[i] = withdrawalRecord.auctionId; _values[i] = withdrawalRecord.value; _times[i] = withdrawalRecord.time; _callTimes[i] = withdrawalRecord.callTime; _hasWithdrawn[i] = withdrawalRecord.hasWithdrawn; } } function getTradeRecord(uint256 _tradeId) external view returns ( uint256 _tokenId, uint256 _auctionId, uint256 _price, uint256 _time, address _owner, address _seller ) { TradeRecord storage _tradeRecord = tradeRecords[_tradeId]; _tokenId = _tradeRecord.tokenId; _auctionId = _tradeRecord.auctionId; _price = _tradeRecord.price; _time = _tradeRecord.time; _owner = _tradeRecord.owner; _seller = _tradeRecord.seller; } function totalTradeRecords() external view returns (uint256) { return tradeRecords.length - 1; // need to exclude the dummy } function getPricesOfLatestTradeRecords(uint256 amount) external view returns (uint256[] memory _prices) { _prices = new uint256[](amount); uint256 startIndex = tradeRecords.length - amount; for(uint256 i = 0 ; i < amount ; i++) { _prices[i] = tradeRecords[startIndex + i].price; } } function getAuctionItem(uint256 _auctionId) external view returns ( uint256 _tokenId, uint256 _basePrice, address _seller, uint256 _startTime, uint256 _endTime, uint256 _state, uint256[] _bidIndexes ) { AuctionItem storage _auctionItem = auctionItems[_auctionId]; _tokenId = _auctionItem.tokenId; _basePrice = _auctionItem.basePrice; _seller = _auctionItem.seller; _startTime = _auctionItem.startTime; _endTime = _auctionItem.endTime; _state = _auctionItem.state; _bidIndexes = _auctionItem.bidIndexes; } function getAuctionItems(uint256[] _auctionIds) external view returns ( uint256[] _tokenId, uint256[] _basePrice, address[] _seller, uint256[] _startTime, uint256[] _endTime, uint256[] _state, uint256[] _lastBidId ) { _tokenId = new uint256[](_auctionIds.length); _basePrice = new uint256[](_auctionIds.length); _startTime = new uint256[](_auctionIds.length); _endTime = new uint256[](_auctionIds.length); _state = new uint256[](_auctionIds.length); _lastBidId = new uint256[](_auctionIds.length); _seller = new address[](_auctionIds.length); for(uint256 i = 0 ; i < _auctionIds.length ; i++) { AuctionItem storage _auctionItem = auctionItems[_auctionIds[i]]; _tokenId[i] = (_auctionItem.tokenId); _basePrice[i] = (_auctionItem.basePrice); _seller[i] = (_auctionItem.seller); _startTime[i] = (_auctionItem.startTime); _endTime[i] = (_auctionItem.endTime); _state[i] = (_auctionItem.state); for(uint256 j = _auctionItem.bidIndexes.length - 1 ; j > 0 ; j--) { if(_auctionItem.bidIndexes[j] > 0) { _lastBidId[i] = _auctionItem.bidIndexes[j]; break; } } } } function totalAuctionItems() external view returns (uint256) { return auctionItems.length - 1; // need to exclude the dummy } function getBid(uint256 _bidId) external view returns ( uint256 _auctionId, uint256 _price, uint256 _time, address _bidder ) { Bid storage _bid = bidHistory[_bidId]; _auctionId = _bid.auctionId; _price = _bid.price; _time = _bid.time; _bidder = _bid.bidder; } function getBids(uint256[] _bidIds) external view returns ( uint256[] _auctionId, uint256[] _price, uint256[] _time, address[] _bidder ) { _auctionId = new uint256[](_bidIds.length); _price = new uint256[](_bidIds.length); _time = new uint256[](_bidIds.length); _bidder = new address[](_bidIds.length); for(uint256 i = 0 ; i < _bidIds.length ; i++) { Bid storage _bid = bidHistory[_bidIds[i]]; _auctionId[i] = _bid.auctionId; _price[i] = _bid.price; _time[i] = _bid.time; _bidder[i] = _bid.bidder; } } // setters function addTradeRecord ( uint256 _tokenId, uint256 _auctionId, uint256 _price, uint256 _time, address _buyer, address _seller ) external returns (uint256 _tradeId) { require(canUpdate()); _tradeId = tradeRecords.length; tradeRecords.push(TradeRecord(_tokenId, _auctionId, _price, uint48(_time), _buyer, _seller)); if(_auctionId > 0) { auctionItems[_auctionId].state = uint8(2); } emit TradeRecordAdded(_seller, _buyer, _tradeId, _price, _tokenId, _auctionId); } function addAuctionItem ( uint256 _tokenId, uint256 _basePrice, address _seller, uint256 _endTime ) external returns (uint256 _auctionId) { require(canUpdate()); _auctionId = auctionItems.length; auctionItems.push(AuctionItem( _tokenId, _basePrice, _seller, uint48(now), uint48(_endTime), 0, new uint256[](21))); emit AuctionItemAdded(_seller, _auctionId, _basePrice, _endTime - now, _tokenId); } function updateAuctionTime(uint256 _auctionId, uint256 _time, uint256 _state) external { require(canUpdate()); AuctionItem storage _auctionItem = auctionItems[_auctionId]; _auctionItem.endTime = uint48(_time); _auctionItem.state = uint8(_state); } function addBidder(uint256 _auctionId, address _bidder, uint256 _price, uint256 _bidIndex) external { require(canUpdate()); uint256 _bidId = bidHistory.length; bidHistory.push(Bid(_auctionId, _price, uint48(now), _bidder)); AuctionItem storage _auctionItem = auctionItems[_auctionId]; // find previous bidder // Max bid index is 20, so maximum loop is 20 times address _previousBidder = address(0); for(uint256 i = _auctionItem.bidIndexes.length - 1 ; i > 0 ; i--) { if(_auctionItem.bidIndexes[i] > 0) { Bid memory _previousBid = bidHistory[_auctionItem.bidIndexes[i]]; _previousBidder = _previousBid.bidder; break; } } _auctionItem.bidIndexes[_bidIndex] = _bidId; emit AuctionBid(_bidder, _previousBidder, _auctionId, _price, _bidIndex, _auctionItem.tokenId, _auctionItem.endTime); } function addWithdrawal ( address _withdrawer, uint256 _auctionId, uint256 _value, uint256 _callTime ) external { require(canUpdate()); WithdrawalRecord memory _withdrawal = WithdrawalRecord(_auctionId, _value, uint48(now), uint48(_callTime), false); withdrawalList[_withdrawer].push(_withdrawal); } function clearPendingWithdrawal(address _withdrawer) external returns (uint256 _withdrawnAmount) { require(canUpdate()); WithdrawalRecord[] storage _withdrawalList = withdrawalList[_withdrawer]; uint256 _lastWithdrawnIndex = lastWithdrawnIndex[_withdrawer]; for(uint256 i = _lastWithdrawnIndex ; i < _withdrawalList.length ; i++) { WithdrawalRecord storage _withdrawalRecord = _withdrawalList[i]; _withdrawalRecord.hasWithdrawn = true; _withdrawnAmount += _withdrawalRecord.value; } // update the last withdrawn index so next time will start from this index lastWithdrawnIndex[_withdrawer] = _withdrawalList.length - 1; emit PendingWithdrawalCleared(_withdrawer, _withdrawnAmount); } } library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } contract SupportsInterfaceWithLookup is ERC165 { bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256(&#39;supportsInterface(bytes4)&#39;)) */ /** * @dev a mapping of interface id to whether or not it&#39;s supported */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev A contract implementing SupportsInterfaceWithLookup * implement ERC165 itself */ constructor() public { _registerInterface(InterfaceId_ERC165); } /** * @dev implement supportsInterface(bytes4) using a lookup table */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return supportedInterfaces[_interfaceId]; } /** * @dev private method for registering an interface */ function _registerInterface(bytes4 _interfaceId) internal { require(_interfaceId != 0xffffffff); supportedInterfaces[_interfaceId] = true; } } 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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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&#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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract CryptantCrabBase is Ownable { GenesisCrabInterface public genesisCrab; CryptantCrabNFT public cryptantCrabToken; CryptantCrabStoreInterface public cryptantCrabStorage; constructor(address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress) public { // constructor _setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress); } function setAddresses( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) external onlyOwner { _setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress); } function _setAddresses( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) internal { if(_genesisCrabAddress != address(0)) { GenesisCrabInterface genesisCrabContract = GenesisCrabInterface(_genesisCrabAddress); genesisCrab = genesisCrabContract; } if(_cryptantCrabTokenAddress != address(0)) { CryptantCrabNFT cryptantCrabTokenContract = CryptantCrabNFT(_cryptantCrabTokenAddress); cryptantCrabToken = cryptantCrabTokenContract; } if(_cryptantCrabStorageAddress != address(0)) { CryptantCrabStoreInterface cryptantCrabStorageContract = CryptantCrabStoreInterface(_cryptantCrabStorageAddress); cryptantCrabStorage = cryptantCrabStorageContract; } } } contract CryptantCrabInformant is CryptantCrabBase{ constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) public CryptantCrabBase ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress ) { // constructor } function _getCrabData(uint256 _tokenId) internal view returns ( uint256 _gene, uint256 _level, uint256 _exp, uint256 _mutationCount, uint256 _trophyCount, uint256 _heartValue, uint256 _growthValue ) { require(cryptantCrabStorage != address(0)); bytes32[] memory keys = new bytes32[](7); uint256[] memory values; keys[0] = keccak256(abi.encodePacked(_tokenId, "gene")); keys[1] = keccak256(abi.encodePacked(_tokenId, "level")); keys[2] = keccak256(abi.encodePacked(_tokenId, "exp")); keys[3] = keccak256(abi.encodePacked(_tokenId, "mutationCount")); keys[4] = keccak256(abi.encodePacked(_tokenId, "trophyCount")); keys[5] = keccak256(abi.encodePacked(_tokenId, "heartValue")); keys[6] = keccak256(abi.encodePacked(_tokenId, "growthValue")); values = cryptantCrabStorage.readUint256s(keys); // process heart value uint256 _processedHeartValue; for(uint256 i = 1 ; i <= 1000 ; i *= 10) { if(uint256(values[5]) / i % 10 > 0) { _processedHeartValue += i; } } _gene = values[0]; _level = values[1]; _exp = values[2]; _mutationCount = values[3]; _trophyCount = values[4]; _heartValue = _processedHeartValue; _growthValue = values[6]; } function _geneOfCrab(uint256 _tokenId) internal view returns (uint256 _gene) { require(cryptantCrabStorage != address(0)); _gene = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "gene"))); } } contract CrabManager is CryptantCrabInformant, CrabData { constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) public CryptantCrabInformant ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress ) { // constructor } function getCrabsOfOwner(address _owner) external view returns (uint256[]) { uint256 _balance = cryptantCrabToken.balanceOf(_owner); uint256[] memory _tokenIds = new uint256[](_balance); for(uint256 i = 0 ; i < _balance ; i++) { _tokenIds[i] = cryptantCrabToken.tokenOfOwnerByIndex(_owner, i); } return _tokenIds; } function getCrab(uint256 _tokenId) external view returns ( uint256 _gene, uint256 _level, uint256 _exp, uint256 _mutationCount, uint256 _trophyCount, uint256 _heartValue, uint256 _growthValue, uint256 _fossilType ) { require(cryptantCrabToken.exists(_tokenId)); (_gene, _level, _exp, _mutationCount, _trophyCount, _heartValue, _growthValue) = _getCrabData(_tokenId); _fossilType = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "fossilType"))); } function getCrabStats(uint256 _tokenId) external view returns ( uint256 _hp, uint256 _dps, uint256 _block, uint256[] _partBonuses, uint256 _fossilAttribute ) { require(cryptantCrabToken.exists(_tokenId)); uint256 _gene = _geneOfCrab(_tokenId); (_hp, _dps, _block) = _getCrabTotalStats(_gene); _partBonuses = _getCrabPartBonuses(_tokenId); _fossilAttribute = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, "fossilAttribute"))); } function _getCrabTotalStats(uint256 _gene) internal view returns ( uint256 _hp, uint256 _dps, uint256 _blockRate ) { CrabPartData[] memory crabPartData = _getCrabPartData(_gene); for(uint256 i = 0 ; i < crabPartData.length ; i++) { _hp += crabPartData[i].hp; _dps += crabPartData[i].dps; _blockRate += crabPartData[i].blockRate; } } function _getCrabPartBonuses(uint256 _tokenId) internal view returns (uint256[] _partBonuses) { bytes32[] memory _keys = new bytes32[](4); _keys[0] = keccak256(abi.encodePacked(_tokenId, uint256(1), "partBonus")); _keys[1] = keccak256(abi.encodePacked(_tokenId, uint256(2), "partBonus")); _keys[2] = keccak256(abi.encodePacked(_tokenId, uint256(3), "partBonus")); _keys[3] = keccak256(abi.encodePacked(_tokenId, uint256(4), "partBonus")); _partBonuses = cryptantCrabStorage.readUint256s(_keys); } function _getCrabPartData(uint256 _gene) internal view returns (CrabPartData[] memory _crabPartData) { require(cryptantCrabToken != address(0)); uint256[] memory _bodyData; uint256[] memory _legData; uint256[] memory _leftClawData; uint256[] memory _rightClawData; (_bodyData, _legData, _leftClawData, _rightClawData) = cryptantCrabToken.crabPartDataFromGene(_gene); _crabPartData = new CrabPartData[](4); _crabPartData[0] = arrayToCrabPartData(_bodyData); _crabPartData[1] = arrayToCrabPartData(_legData); _crabPartData[2] = arrayToCrabPartData(_leftClawData); _crabPartData[3] = arrayToCrabPartData(_rightClawData); } } contract CryptantCrabPurchasableLaunch is CryptantCrabInformant { using SafeMath for uint256; Transmuter public transmuter; event CrabHatched(address indexed owner, uint256 tokenId, uint256 gene, uint256 specialSkin, uint256 crabPrice, uint256 growthValue); event CryptantFragmentsAdded(address indexed cryptantOwner, uint256 amount, uint256 newBalance); event CryptantFragmentsRemoved(address indexed cryptantOwner, uint256 amount, uint256 newBalance); event Refund(address indexed refundReceiver, uint256 reqAmt, uint256 paid, uint256 refundAmt); constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress, address _transmuterAddress ) public CryptantCrabInformant ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress ) { // constructor if(_transmuterAddress != address(0)) { _setTransmuterAddress(_transmuterAddress); } } function setAddresses( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress, address _transmuterAddress ) external onlyOwner { _setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress); if(_transmuterAddress != address(0)) { _setTransmuterAddress(_transmuterAddress); } } function _setTransmuterAddress(address _transmuterAddress) internal { Transmuter _transmuterContract = Transmuter(_transmuterAddress); transmuter = _transmuterContract; } function getCryptantFragments(address _sender) public view returns (uint256) { return cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_sender, "cryptant"))); } function createCrab(uint256 _customTokenId, uint256 _crabPrice, uint256 _customGene, uint256 _customSkin, bool _hasLegendary) external onlyOwner { _createCrab(_customTokenId, _crabPrice, _customGene, _customSkin, _hasLegendary); } function _addCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) { _newBalance = getCryptantFragments(_cryptantOwner).add(_amount); cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance); emit CryptantFragmentsAdded(_cryptantOwner, _amount, _newBalance); } function _removeCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) { _newBalance = getCryptantFragments(_cryptantOwner).sub(_amount); cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance); emit CryptantFragmentsRemoved(_cryptantOwner, _amount, _newBalance); } function _createCrab(uint256 _tokenId, uint256 _crabPrice, uint256 _customGene, uint256 _customSkin, bool _hasLegendary) internal { uint256[] memory _values = new uint256[](8); bytes32[] memory _keys = new bytes32[](8); uint256 _gene; uint256 _specialSkin; uint256 _heartValue; uint256 _growthValue; if(_customGene == 0) { (_gene, _specialSkin, _heartValue, _growthValue) = genesisCrab.generateCrabGene(false, _hasLegendary); } else { _gene = _customGene; } if(_customSkin != 0) { _specialSkin = _customSkin; } (_heartValue, _growthValue) = genesisCrab.generateCrabHeart(); cryptantCrabToken.mintToken(msg.sender, _tokenId, _specialSkin); // Gene pair _keys[0] = keccak256(abi.encodePacked(_tokenId, "gene")); _values[0] = _gene; // Level pair _keys[1] = keccak256(abi.encodePacked(_tokenId, "level")); _values[1] = 1; // Heart Value pair _keys[2] = keccak256(abi.encodePacked(_tokenId, "heartValue")); _values[2] = _heartValue; // Growth Value pair _keys[3] = keccak256(abi.encodePacked(_tokenId, "growthValue")); _values[3] = _growthValue; // Handling Legendary Bonus uint256[] memory _partLegendaryBonuses = transmuter.generateBonusForGene(_gene); // body _keys[4] = keccak256(abi.encodePacked(_tokenId, uint256(1), "partBonus")); _values[4] = _partLegendaryBonuses[0]; // legs _keys[5] = keccak256(abi.encodePacked(_tokenId, uint256(2), "partBonus")); _values[5] = _partLegendaryBonuses[1]; // left claw _keys[6] = keccak256(abi.encodePacked(_tokenId, uint256(3), "partBonus")); _values[6] = _partLegendaryBonuses[2]; // right claw _keys[7] = keccak256(abi.encodePacked(_tokenId, uint256(4), "partBonus")); _values[7] = _partLegendaryBonuses[3]; require(cryptantCrabStorage.createUint256s(_keys, _values)); emit CrabHatched(msg.sender, _tokenId, _gene, _specialSkin, _crabPrice, _growthValue); } function _refundExceededValue(uint256 _senderValue, uint256 _requiredValue) internal { uint256 _exceededValue = _senderValue.sub(_requiredValue); if(_exceededValue > 0) { msg.sender.transfer(_exceededValue); emit Refund(msg.sender, _requiredValue, _senderValue, _exceededValue); } } } contract CryptantInformant is CryptantCrabInformant { using SafeMath for uint256; event CryptantFragmentsAdded(address indexed cryptantOwner, uint256 amount, uint256 newBalance); event CryptantFragmentsRemoved(address indexed cryptantOwner, uint256 amount, uint256 newBalance); constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) public CryptantCrabInformant ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress ) { // constructor } function getCryptantFragments(address _sender) public view returns (uint256) { return cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_sender, "cryptant"))); } function _addCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) { _newBalance = getCryptantFragments(_cryptantOwner).add(_amount); cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance); emit CryptantFragmentsAdded(_cryptantOwner, _amount, _newBalance); } function _removeCryptantFragments(address _cryptantOwner, uint256 _amount) internal returns (uint256 _newBalance) { _newBalance = getCryptantFragments(_cryptantOwner).sub(_amount); cryptantCrabStorage.updateUint256(keccak256(abi.encodePacked(_cryptantOwner, "cryptant")), _newBalance); emit CryptantFragmentsRemoved(_cryptantOwner, _amount, _newBalance); } } contract Transmuter is CryptantInformant, GeneSurgeon, Randomable, LevelCalculator { event Xenografted(address indexed tokenOwner, uint256 recipientTokenId, uint256 donorTokenId, uint256 oldPartGene, uint256 newPartGene, uint256 oldPartBonus, uint256 newPartBonus, uint256 xenograftPart); event Mutated(address indexed tokenOwner, uint256 tokenId, uint256 partIndex, uint256 oldGene, uint256 newGene, uint256 oldPartBonus, uint256 newPartBonus, uint256 mutationCount); /** * @dev Pre-generated keys to save gas * keys are generated with: * NORMAL_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("normalFossilRelicPercentage")) = 0xcaf6fae2 * PIONEER_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("pioneerFossilRelicPercentage")) = 0x04988c65 * LEGENDARY_FOSSIL_RELIC_PERCENTAGE = bytes4(keccak256("legendaryFossilRelicPercentage")) = 0x277e613a * FOSSIL_ATTRIBUTE_COUNT = bytes4(keccak256("fossilAttributesCount")) = 0x06c475be * LEGENDARY_BONUS_COUNT = bytes4(keccak256("legendaryBonusCount")) = 0x45025094 * LAST_PIONEER_TOKEN_ID = bytes4(keccak256("lastPioneerTokenId")) = 0xe562bae2 */ bytes4 internal constant NORMAL_FOSSIL_RELIC_PERCENTAGE = 0xcaf6fae2; bytes4 internal constant PIONEER_FOSSIL_RELIC_PERCENTAGE = 0x04988c65; bytes4 internal constant LEGENDARY_FOSSIL_RELIC_PERCENTAGE = 0x277e613a; bytes4 internal constant FOSSIL_ATTRIBUTE_COUNT = 0x06c475be; bytes4 internal constant LEGENDARY_BONUS_COUNT = 0x45025094; bytes4 internal constant LAST_PIONEER_TOKEN_ID = 0xe562bae2; mapping(bytes4 => uint256) internal internalUintVariable; // elements => legendary set index of that element mapping(uint256 => uint256[]) internal legendaryPartIndex; constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress ) public CryptantInformant ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress ) { // constructor // default values for relic percentages // normal crab relic is set to 5% _setUint(NORMAL_FOSSIL_RELIC_PERCENTAGE, 5000); // pioneer crab relic is set to 50% _setUint(PIONEER_FOSSIL_RELIC_PERCENTAGE, 50000); // legendary crab part relic is set to increase by 50% _setUint(LEGENDARY_FOSSIL_RELIC_PERCENTAGE, 50000); // The max number of attributes types // Every fossil will have 1 attribute _setUint(FOSSIL_ATTRIBUTE_COUNT, 6); // The max number of bonus types for legendary // Every legendary will have 1 bonus _setUint(LEGENDARY_BONUS_COUNT, 5); // The last pioneer token ID to be referred as Pioneer _setUint(LAST_PIONEER_TOKEN_ID, 1121); } function setPartIndex(uint256 _element, uint256[] _partIndexes) external onlyOwner { legendaryPartIndex[_element] = _partIndexes; } function getPartIndexes(uint256 _element) external view onlyOwner returns (uint256[] memory _partIndexes){ _partIndexes = legendaryPartIndex[_element]; } function getUint(bytes4 key) external view returns (uint256 value) { value = _getUint(key); } function setUint(bytes4 key, uint256 value) external onlyOwner { _setUint(key, value); } function _getUint(bytes4 key) internal view returns (uint256 value) { value = internalUintVariable[key]; } function _setUint(bytes4 key, uint256 value) internal { internalUintVariable[key] = value; } function xenograft(uint256 _recipientTokenId, uint256 _donorTokenId, uint256 _xenograftPart) external { // get crab gene of both token // make sure both token is not fossil // replace the recipient part with donor part // mark donor as fosil // fosil will generate 1 attr // 3% of fosil will have relic // deduct 10 cryptant require(_xenograftPart != 1); // part cannot be body (part index = 1) require(cryptantCrabToken.ownerOf(_recipientTokenId) == msg.sender); // check ownership of both token require(cryptantCrabToken.ownerOf(_donorTokenId) == msg.sender); // due to stack too deep, need to use an array // to represent all the variables uint256[] memory _intValues = new uint256[](11); _intValues[0] = getCryptantFragments(msg.sender); // _intValues[0] = ownedCryptant // _intValues[1] = donorPartBonus // _intValues[2] = recipientGene // _intValues[3] = donorGene // _intValues[4] = recipientPart // _intValues[5] = donorPart // _intValues[6] = relicPercentage // _intValues[7] = fossilType // _intValues[8] = recipientExistingPartBonus // _intValues[9] = recipientLevel // _intValues[10] = recipientExp // perform transplant requires 5 cryptant require(_intValues[0] >= 5000); // make sure both tokens are not fossil uint256[] memory _values; bytes32[] memory _keys = new bytes32[](6); _keys[0] = keccak256(abi.encodePacked(_recipientTokenId, "fossilType")); _keys[1] = keccak256(abi.encodePacked(_donorTokenId, "fossilType")); _keys[2] = keccak256(abi.encodePacked(_donorTokenId, _xenograftPart, "partBonus")); _keys[3] = keccak256(abi.encodePacked(_recipientTokenId, _xenograftPart, "partBonus")); _keys[4] = keccak256(abi.encodePacked(_recipientTokenId, "level")); _keys[5] = keccak256(abi.encodePacked(_recipientTokenId, "exp")); _values = cryptantCrabStorage.readUint256s(_keys); require(_values[0] == 0); require(_values[1] == 0); _intValues[1] = _values[2]; _intValues[8] = _values[3]; // _values[5] = recipient Exp // _values[4] = recipient Level _intValues[9] = _values[4]; _intValues[10] = _values[5]; // Increase Exp _intValues[10] += 8; // check if crab level up uint256 _expRequired = expRequiredToReachLevel(_intValues[9] + 1); if(_intValues[10] >=_expRequired) { // increase level _intValues[9] += 1; // carry forward extra exp _intValues[10] -= _expRequired; emit LevelUp(msg.sender, _recipientTokenId, _intValues[9], _intValues[10]); } else { emit ExpGained(msg.sender, _recipientTokenId, _intValues[9], _intValues[10]); } // start performing Xenograft _intValues[2] = _geneOfCrab(_recipientTokenId); _intValues[3] = _geneOfCrab(_donorTokenId); // recipientPart _intValues[4] = _intValues[2] / crabPartMultiplier[_xenograftPart] % 1000; _intValues[5] = _intValues[3] / crabPartMultiplier[_xenograftPart] % 1000; int256 _partDiff = int256(_intValues[4]) - int256(_intValues[5]); _intValues[2] = uint256(int256(_intValues[2]) - (_partDiff * int256(crabPartMultiplier[_xenograftPart]))); _values = new uint256[](6); _keys = new bytes32[](6); // Gene pair _keys[0] = keccak256(abi.encodePacked(_recipientTokenId, "gene")); _values[0] = _intValues[2]; // Fossil Attribute _keys[1] = keccak256(abi.encodePacked(_donorTokenId, "fossilAttribute")); _values[1] = _generateRandomNumber(bytes32(_intValues[2] + _intValues[3] + _xenograftPart), _getUint(FOSSIL_ATTRIBUTE_COUNT)) + 1; // intVar1 will now use to store relic percentage variable if(isLegendaryPart(_intValues[3], 1)) { // if body part is legendary 100% become relic _intValues[7] = 2; } else { // Relic percentage will differ depending on the crab type / rarity _intValues[6] = _getUint(NORMAL_FOSSIL_RELIC_PERCENTAGE); if(_donorTokenId <= _getUint(LAST_PIONEER_TOKEN_ID)) { _intValues[6] = _getUint(PIONEER_FOSSIL_RELIC_PERCENTAGE); } if(isLegendaryPart(_intValues[3], 2) || isLegendaryPart(_intValues[3], 3) || isLegendaryPart(_intValues[3], 4)) { _intValues[6] += _getUint(LEGENDARY_FOSSIL_RELIC_PERCENTAGE); } // Fossil Type // 1 = Normal Fossil // 2 = Relic Fossil _intValues[7] = 1; if(_generateRandomNumber(bytes32(_intValues[3] + _xenograftPart), 100000) < _intValues[6]) { _intValues[7] = 2; } } _keys[2] = keccak256(abi.encodePacked(_donorTokenId, "fossilType")); _values[2] = _intValues[7]; // Part Attribute _keys[3] = keccak256(abi.encodePacked(_recipientTokenId, _xenograftPart, "partBonus")); _values[3] = _intValues[1]; // Recipient Level _keys[4] = keccak256(abi.encodePacked(_recipientTokenId, "level")); _values[4] = _intValues[9]; // Recipient Exp _keys[5] = keccak256(abi.encodePacked(_recipientTokenId, "exp")); _values[5] = _intValues[10]; require(cryptantCrabStorage.updateUint256s(_keys, _values)); _removeCryptantFragments(msg.sender, 5000); emit Xenografted(msg.sender, _recipientTokenId, _donorTokenId, _intValues[4], _intValues[5], _intValues[8], _intValues[1], _xenograftPart); } function mutate(uint256 _tokenId, uint256 _partIndex) external { // token must be owned by sender require(cryptantCrabToken.ownerOf(_tokenId) == msg.sender); // body part cannot mutate require(_partIndex > 1 && _partIndex < 5); // here not checking if sender has enough cryptant // is because _removeCryptantFragments uses safeMath // to do subtract, so it will revert if it&#39;s not enough _removeCryptantFragments(msg.sender, 1000); bytes32[] memory _keys = new bytes32[](5); _keys[0] = keccak256(abi.encodePacked(_tokenId, "gene")); _keys[1] = keccak256(abi.encodePacked(_tokenId, "level")); _keys[2] = keccak256(abi.encodePacked(_tokenId, "exp")); _keys[3] = keccak256(abi.encodePacked(_tokenId, "mutationCount")); _keys[4] = keccak256(abi.encodePacked(_tokenId, _partIndex, "partBonus")); uint256[] memory _values = new uint256[](5); (_values[0], _values[1], _values[2], _values[3], , , ) = _getCrabData(_tokenId); uint256[] memory _partsGene = new uint256[](5); uint256 i; for(i = 1 ; i <= 4 ; i++) { _partsGene[i] = _values[0] / crabPartMultiplier[i] % 1000; } // mutate starts from 3%, max is 20% which is 170 mutations if(_values[3] > 170) { _values[3] = 170; } uint256 newPartGene = genesisCrab.mutateCrabPart(_partIndex, _partsGene[_partIndex], (30 + _values[3]) * 100); //generate the new gene uint256 _oldPartBonus = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(_tokenId, _partIndex, "partBonus"))); uint256 _partGene; // this variable will be reused by oldGene uint256 _newGene; for(i = 1 ; i <= 4 ; i++) { _partGene = _partsGene[i]; if(i == _partIndex) { _partGene = newPartGene; } _newGene += _partGene * crabPartMultiplier[i]; } if(isLegendaryPart(_newGene, _partIndex)) { _values[4] = _generateRandomNumber(bytes32(_newGene + _partIndex + _tokenId), _getUint(LEGENDARY_BONUS_COUNT)) + 1; } // Reuse partGene as old gene _partGene = _values[0]; // New Gene _values[0] = _newGene; // Increase Exp _values[2] += 8; // check if crab level up uint256 _expRequired = expRequiredToReachLevel(_values[1] + 1); if(_values[2] >=_expRequired) { // increase level _values[1] += 1; // carry forward extra exp _values[2] -= _expRequired; emit LevelUp(msg.sender, _tokenId, _values[1], _values[2]); } else { emit ExpGained(msg.sender, _tokenId, _values[1], _values[2]); } // Increase Mutation Count _values[3] += 1; require(cryptantCrabStorage.updateUint256s(_keys, _values)); emit Mutated(msg.sender, _tokenId, _partIndex, _partGene, _newGene, _oldPartBonus, _values[4], _values[3]); } function generateBonusForGene(uint256 _gene) external view returns (uint256[] _bonuses) { _bonuses = new uint256[](4); uint256[] memory _elements = extractElementsFromGene(_gene); uint256[] memory _parts = extractPartsFromGene(_gene); uint256[] memory _legendaryParts; for(uint256 i = 0 ; i < 4 ; i++) { _legendaryParts = legendaryPartIndex[_elements[i]]; for(uint256 j = 0 ; j < _legendaryParts.length ; j++) { if(_legendaryParts[j] == _parts[i]) { // generate the bonus number and add it into the _bonuses array _bonuses[i] = _generateRandomNumber(bytes32(_gene + i), _getUint(LEGENDARY_BONUS_COUNT)) + 1; break; } } } } /** * @dev checks if the specified part of the given gene is a legendary part or not * returns true if its a legendary part, false otherwise. * @param _gene full body gene to be checked on * @param _part partIndex ranging from 1 = body, 2 = legs, 3 = left claw, 4 = right claw */ function isLegendaryPart(uint256 _gene, uint256 _part) internal view returns (bool) { uint256[] memory _legendaryParts = legendaryPartIndex[extractElementsFromGene(_gene)[_part - 1]]; for(uint256 i = 0 ; i < _legendaryParts.length ; i++) { if(_legendaryParts[i] == extractPartsFromGene(_gene)[_part - 1]) { return true; } } return false; } } contract Withdrawable is Ownable { address public withdrawer; /** * @dev Throws if called by any account other than the withdrawer. */ modifier onlyWithdrawer() { require(msg.sender == withdrawer); _; } function setWithdrawer(address _newWithdrawer) external onlyOwner { withdrawer = _newWithdrawer; } /** * @dev withdraw the specified amount of ether from contract. * @param _amount the amount of ether to withdraw. Units in wei. */ function withdraw(uint256 _amount) external onlyWithdrawer returns(bool) { require(_amount <= address(this).balance); withdrawer.transfer(_amount); return true; } } contract CryptantCrabMarket is CryptantCrabPurchasableLaunch, GeneSurgeon, Randomable, Withdrawable { event Purchased(address indexed owner, uint256 amount, uint256 cryptant, uint256 refund); event ReferralPurchase(address indexed referral, uint256 rewardAmount, address buyer); event CrabOnSaleStarted(address indexed seller, uint256 tokenId, uint256 sellingPrice, uint256 marketId, uint256 gene); event CrabOnSaleCancelled(address indexed seller, uint256 tokenId, uint256 marketId); event Traded(address indexed seller, address indexed buyer, uint256 tokenId, uint256 tradedPrice, uint256 marketId); // Trade Type 0 = Purchase struct MarketItem { uint256 tokenId; uint256 sellingPrice; address seller; uint8 state; // 1 - on going, 2 - cancelled, 3 - completed } PrizePool public prizePool; /** * @dev Pre-generated keys to save gas * keys are generated with: * MARKET_PRICE_UPDATE_PERIOD = bytes4(keccak256("marketPriceUpdatePeriod")) = 0xf1305a10 * CURRENT_TOKEN_ID = bytes4(keccak256("currentTokenId")) = 0x21339464 * REFERRAL_CUT = bytes4(keccak256("referralCut")) = 0x40b0b13e * PURCHASE_PRIZE_POOL_CUT = bytes4(keccak256("purchasePrizePoolCut")) = 0x7625c58a * EXCHANGE_PRIZE_POOL_CUT = bytes4(keccak256("exchangePrizePoolCut")) = 0xb9e1adb0 * EXCHANGE_DEVELOPER_CUT = bytes4(keccak256("exchangeDeveloperCut")) = 0xfe9ad0eb * LAST_TRANSACTION_PERIOD = bytes4(keccak256("lastTransactionPeriod")) = 0x1a01d5bb * LAST_TRANSACTION_PRICE = bytes4(keccak256("lastTransactionPrice")) = 0xf14adb6a */ bytes4 internal constant MARKET_PRICE_UPDATE_PERIOD = 0xf1305a10; bytes4 internal constant CURRENT_TOKEN_ID = 0x21339464; bytes4 internal constant REFERRAL_CUT = 0x40b0b13e; bytes4 internal constant PURCHASE_PRIZE_POOL_CUT = 0x7625c58a; bytes4 internal constant EXCHANGE_PRIZE_POOL_CUT = 0xb9e1adb0; bytes4 internal constant EXCHANGE_DEVELOPER_CUT = 0xfe9ad0eb; bytes4 internal constant LAST_TRANSACTION_PERIOD = 0x1a01d5bb; bytes4 internal constant LAST_TRANSACTION_PRICE = 0xf14adb6a; /** * @dev The first 25 trading crab price will be fixed to 0.3 ether. * This only applies to crab bought from developer. * Crab on auction will depends on the price set by owner. */ uint256 constant public initialCrabTradingPrice = 300 finney; // The initial cryptant price will be fixed to 0.03 ether. // It will changed to dynamic price after 25 crabs traded. // 1000 Cryptant Fragment = 1 Cryptant. uint256 constant public initialCryptantFragmentTradingPrice = 30 szabo; mapping(bytes4 => uint256) internal internalUintVariable; // All traded price will be stored here uint256[] public tradedPrices; // All auctioned items will be stored here MarketItem[] public marketItems; // PrizePool key, default value is 0xadd5d43f // 0xadd5d43f = bytes4(keccak256(bytes("firstPrizePool"))); bytes4 public currentPrizePool = 0xadd5d43f; constructor ( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress, address _transmuterAddress, address _prizePoolAddress ) public CryptantCrabPurchasableLaunch ( _genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress, _transmuterAddress ) { // constructor if(_prizePoolAddress != address(0)) { _setPrizePoolAddress(_prizePoolAddress); } // set the initial token id _setUint(CURRENT_TOKEN_ID, 1121); // The number of seconds that the market will stay at fixed price. // Default set to 4 hours _setUint(MARKET_PRICE_UPDATE_PERIOD, 14400); // The percentage of referral cut // Default set to 10% _setUint(REFERRAL_CUT, 10000); // The percentage of price pool cut when purchase a new crab // Default set to 20% _setUint(PURCHASE_PRIZE_POOL_CUT, 20000); // The percentage of prize pool cut when market exchange traded // Default set to 2% _setUint(EXCHANGE_PRIZE_POOL_CUT, 2000); // The percentage of developer cut // Default set to 2.8% _setUint(EXCHANGE_DEVELOPER_CUT, 2800); // to prevent marketId = 0 // put a dummy value for it marketItems.push(MarketItem(0, 0, address(0), 0)); } function _setPrizePoolAddress(address _prizePoolAddress) internal { PrizePool _prizePoolContract = PrizePool(_prizePoolAddress); prizePool = _prizePoolContract; } function setAddresses( address _genesisCrabAddress, address _cryptantCrabTokenAddress, address _cryptantCrabStorageAddress, address _transmuterAddress, address _prizePoolAddress ) external onlyOwner { _setAddresses(_genesisCrabAddress, _cryptantCrabTokenAddress, _cryptantCrabStorageAddress); if(_transmuterAddress != address(0)) { _setTransmuterAddress(_transmuterAddress); } if(_prizePoolAddress != address(0)) { _setPrizePoolAddress(_prizePoolAddress); } } function setCurrentPrizePool(bytes4 _newPrizePool) external onlyOwner { currentPrizePool = _newPrizePool; } function getUint(bytes4 key) external view returns (uint256 value) { value = _getUint(key); } function setUint(bytes4 key, uint256 value) external onlyOwner { _setUint(key, value); } function _getUint(bytes4 key) internal view returns (uint256 value) { value = internalUintVariable[key]; } function _setUint(bytes4 key, uint256 value) internal { internalUintVariable[key] = value; } function purchase(uint256 _crabAmount, uint256 _cryptantFragmentAmount, address _referral) external payable { require(_crabAmount >= 0 && _crabAmount <= 10 ); require(_cryptantFragmentAmount >= 0 && _cryptantFragmentAmount <= 10000); require(!(_crabAmount == 0 && _cryptantFragmentAmount == 0)); require(_cryptantFragmentAmount % 1000 == 0); require(msg.sender != _referral); // check if ether payment is enough uint256 _singleCrabPrice = getCurrentCrabPrice(); uint256 _totalCrabPrice = _singleCrabPrice * _crabAmount; uint256 _totalCryptantPrice = getCurrentCryptantFragmentPrice() * _cryptantFragmentAmount; uint256 _cryptantFragmentsGained = _cryptantFragmentAmount; // free 2 cryptant when purchasing 10 if(_cryptantFragmentsGained == 10000) { _cryptantFragmentsGained += 2000; } uint256 _totalPrice = _totalCrabPrice + _totalCryptantPrice; uint256 _value = msg.value; require(_value >= _totalPrice); // Purchase 10 crabs will have 1 crab with legendary part // Default value for _crabWithLegendaryPart is just a unreacable number uint256 _currentTokenId = _getUint(CURRENT_TOKEN_ID); uint256 _crabWithLegendaryPart = 100; if(_crabAmount == 10) { // decide which crab will have the legendary part _crabWithLegendaryPart = _generateRandomNumber(bytes32(_currentTokenId), 10); } for(uint256 i = 0 ; i < _crabAmount ; i++) { // 5000 ~ 5500 is gift token // so if hit 5000 will skip to 5500 onwards if(_currentTokenId == 5000) { _currentTokenId = 5500; } _currentTokenId++; _createCrab(_currentTokenId, _singleCrabPrice, 0, 0, _crabWithLegendaryPart == i); tradedPrices.push(_singleCrabPrice); } if(_cryptantFragmentsGained > 0) { _addCryptantFragments(msg.sender, (_cryptantFragmentsGained)); } _setUint(CURRENT_TOKEN_ID, _currentTokenId); // Refund exceeded value _refundExceededValue(_value, _totalPrice); // If there&#39;s referral, will transfer the referral reward to the referral if(_referral != address(0)) { uint256 _referralReward = _totalPrice * _getUint(REFERRAL_CUT) / 100000; _referral.transfer(_referralReward); emit ReferralPurchase(_referral, _referralReward, msg.sender); } // Send prize pool cut to prize pool uint256 _prizePoolAmount = _totalPrice * _getUint(PURCHASE_PRIZE_POOL_CUT) / 100000; prizePool.increasePrizePool.value(_prizePoolAmount)(currentPrizePool); _setUint(LAST_TRANSACTION_PERIOD, now / _getUint(MARKET_PRICE_UPDATE_PERIOD)); _setUint(LAST_TRANSACTION_PRICE, _singleCrabPrice); emit Purchased(msg.sender, _crabAmount, _cryptantFragmentsGained, _value - _totalPrice); } function getCurrentPeriod() external view returns (uint256 _now, uint256 _currentPeriod) { _now = now; _currentPeriod = now / _getUint(MARKET_PRICE_UPDATE_PERIOD); } function getCurrentCrabPrice() public view returns (uint256) { if(totalCrabTraded() > 25) { uint256 _lastTransactionPeriod = _getUint(LAST_TRANSACTION_PERIOD); uint256 _lastTransactionPrice = _getUint(LAST_TRANSACTION_PRICE); if(_lastTransactionPeriod == now / _getUint(MARKET_PRICE_UPDATE_PERIOD) && _lastTransactionPrice != 0) { return _lastTransactionPrice; } else { uint256 totalPrice; for(uint256 i = 1 ; i <= 15 ; i++) { totalPrice += tradedPrices[tradedPrices.length - i]; } // the actual calculation here is: // average price = totalPrice / 15 return totalPrice / 15; } } else { return initialCrabTradingPrice; } } function getCurrentCryptantFragmentPrice() public view returns (uint256 _price) { if(totalCrabTraded() > 25) { // real calculation is 1 Cryptant = 10% of currentCrabPrice // should be written as getCurrentCrabPrice() * 10 / 100 / 1000 return getCurrentCrabPrice() * 10 / 100000; } else { return initialCryptantFragmentTradingPrice; } } // After pre-sale crab tracking (excluding fossil transactions) function totalCrabTraded() public view returns (uint256) { return tradedPrices.length; } function sellCrab(uint256 _tokenId, uint256 _sellingPrice) external { require(cryptantCrabToken.ownerOf(_tokenId) == msg.sender); require(_sellingPrice >= 50 finney && _sellingPrice <= 100 ether); marketItems.push(MarketItem(_tokenId, _sellingPrice, msg.sender, 1)); // escrow cryptantCrabToken.transferFrom(msg.sender, address(this), _tokenId); uint256 _gene = _geneOfCrab(_tokenId); emit CrabOnSaleStarted(msg.sender, _tokenId, _sellingPrice, marketItems.length - 1, _gene); } function cancelOnSaleCrab(uint256 _marketId) external { MarketItem storage marketItem = marketItems[_marketId]; // Only able to cancel on sale Item require(marketItem.state == 1); // Set Market Item state to 2(Cancelled) marketItem.state = 2; // Only owner can cancel on sale item require(marketItem.seller == msg.sender); // Release escrow to the owner cryptantCrabToken.transferFrom(address(this), msg.sender, marketItem.tokenId); emit CrabOnSaleCancelled(msg.sender, marketItem.tokenId, _marketId); } function buyCrab(uint256 _marketId) external payable { MarketItem storage marketItem = marketItems[_marketId]; require(marketItem.state == 1); // make sure the sale is on going require(marketItem.sellingPrice == msg.value); require(marketItem.seller != msg.sender); cryptantCrabToken.safeTransferFrom(address(this), msg.sender, marketItem.tokenId); uint256 _developerCut = msg.value * _getUint(EXCHANGE_DEVELOPER_CUT) / 100000; uint256 _prizePoolCut = msg.value * _getUint(EXCHANGE_PRIZE_POOL_CUT) / 100000; uint256 _sellerAmount = msg.value - _developerCut - _prizePoolCut; marketItem.seller.transfer(_sellerAmount); // Send prize pool cut to prize pool prizePool.increasePrizePool.value(_prizePoolCut)(currentPrizePool); uint256 _fossilType = cryptantCrabStorage.readUint256(keccak256(abi.encodePacked(marketItem.tokenId, "fossilType"))); if(_fossilType > 0) { tradedPrices.push(marketItem.sellingPrice); } marketItem.state = 3; _setUint(LAST_TRANSACTION_PERIOD, now / _getUint(MARKET_PRICE_UPDATE_PERIOD)); _setUint(LAST_TRANSACTION_PRICE, getCurrentCrabPrice()); emit Traded(marketItem.seller, msg.sender, marketItem.tokenId, marketItem.sellingPrice, _marketId); } function() public payable { revert(); } } contract HasNoEther is Ownable { /** * @dev Constructor that rejects incoming Ether * The `payable` flag is added so we can access `msg.value` without compiler warning. If we * leave out payable, then Solidity will allow inheriting contracts to implement a payable * constructor. By doing it this way we prevent a payable constructor from working. Alternatively * we could use assembly to access msg.value. */ constructor() public payable { require(msg.value == 0); } /** * @dev Disallows direct send by settings a default function without the `payable` flag. */ function() external { } /** * @dev Transfer all Ether held by the contract to the owner. */ function reclaimEther() external onlyOwner { owner.transfer(address(this).balance); } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } contract Whitelist is Ownable, RBAC { string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev add an address to the whitelist * @param _operator address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address _operator) onlyOwner public { addRole(_operator, ROLE_WHITELISTED); } /** * @dev getter to determine if address is in whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev add addresses to the whitelist * @param _operators addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev remove an address from the whitelist * @param _operator address * @return true if the address was removed from the whitelist, * false if the address wasn&#39;t in the whitelist in the first place */ function removeAddressFromWhitelist(address _operator) onlyOwner public { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev remove addresses from the whitelist * @param _operators addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren&#39;t in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] _operators) onlyOwner public { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract PrizePool is Ownable, Whitelist, HasNoEther { event PrizePoolIncreased(uint256 amountIncreased, bytes4 prizePool, uint256 currentAmount); event WinnerAdded(address winner, bytes4 prizeTitle, uint256 claimableAmount); event PrizedClaimed(address winner, bytes4 prizeTitle, uint256 claimedAmount); // prizePool key => prizePool accumulated amount // this is just to track how much a prizePool has mapping(bytes4 => uint256) prizePools; // winner&#39;s address => prize title => amount // prize title itself need to be able to determine // the prize pool it is from mapping(address => mapping(bytes4 => uint256)) winners; constructor() public { } function increasePrizePool(bytes4 _prizePool) external payable onlyIfWhitelisted(msg.sender) { prizePools[_prizePool] += msg.value; emit PrizePoolIncreased(msg.value, _prizePool, prizePools[_prizePool]); } function addWinner(address _winner, bytes4 _prizeTitle, uint256 _claimableAmount) external onlyIfWhitelisted(msg.sender) { winners[_winner][_prizeTitle] = _claimableAmount; emit WinnerAdded(_winner, _prizeTitle, _claimableAmount); } function claimPrize(bytes4 _prizeTitle) external { uint256 _claimableAmount = winners[msg.sender][_prizeTitle]; require(_claimableAmount > 0); msg.sender.transfer(_claimableAmount); winners[msg.sender][_prizeTitle] = 0; emit PrizedClaimed(msg.sender, _prizeTitle, _claimableAmount); } function claimableAmount(address _winner, bytes4 _prizeTitle) external view returns (uint256 _claimableAmount) { _claimableAmount = winners[_winner][_prizeTitle]; } function prizePoolTotal(bytes4 _prizePool) external view returns (uint256 _prizePoolTotal) { _prizePoolTotal = prizePools[_prizePool]; } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address&#39; access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract ERC721Basic is ERC165 { event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256(&#39;balanceOf(address)&#39;)) ^ * bytes4(keccak256(&#39;ownerOf(uint256)&#39;)) ^ * bytes4(keccak256(&#39;approve(address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;getApproved(uint256)&#39;)) ^ * bytes4(keccak256(&#39;setApprovalForAll(address,bool)&#39;)) ^ * bytes4(keccak256(&#39;isApprovedForAll(address,address)&#39;)) ^ * bytes4(keccak256(&#39;transferFrom(address,address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;safeTransferFrom(address,address,uint256,bytes)&#39;)) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256(&#39;exists(uint256)&#39;)) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } constructor() public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721); _registerInterface(InterfaceId_ERC721Exists); } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256(&#39;totalSupply()&#39;)) ^ * bytes4(keccak256(&#39;tokenOfOwnerByIndex(address,uint256)&#39;)) ^ * bytes4(keccak256(&#39;tokenByIndex(uint256)&#39;)) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256(&#39;name()&#39;)) ^ * bytes4(keccak256(&#39;symbol()&#39;)) ^ * bytes4(keccak256(&#39;tokenURI(uint256)&#39;)) */ // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ constructor(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(InterfaceId_ERC721Enumerable); _registerInterface(InterfaceId_ERC721Metadata); } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } contract CryptantCrabNFT is ERC721Token, Whitelist, CrabData, GeneSurgeon { event CrabPartAdded(uint256 hp, uint256 dps, uint256 blockAmount); event GiftTransfered(address indexed _from, address indexed _to, uint256 indexed _tokenId); event DefaultMetadataURIChanged(string newUri); /** * @dev Pre-generated keys to save gas * keys are generated with: * CRAB_BODY = bytes4(keccak256("crab_body")) = 0xc398430e * CRAB_LEG = bytes4(keccak256("crab_leg")) = 0x889063b1 * CRAB_LEFT_CLAW = bytes4(keccak256("crab_left_claw")) = 0xdb6290a2 * CRAB_RIGHT_CLAW = bytes4(keccak256("crab_right_claw")) = 0x13453f89 */ bytes4 internal constant CRAB_BODY = 0xc398430e; bytes4 internal constant CRAB_LEG = 0x889063b1; bytes4 internal constant CRAB_LEFT_CLAW = 0xdb6290a2; bytes4 internal constant CRAB_RIGHT_CLAW = 0x13453f89; /** * @dev Stores all the crab data */ mapping(bytes4 => mapping(uint256 => CrabPartData[])) internal crabPartData; /** * @dev Mapping from tokenId to its corresponding special skin * tokenId with default skin will not be stored. */ mapping(uint256 => uint256) internal crabSpecialSkins; /** * @dev default MetadataURI */ string public defaultMetadataURI = "https://www.cryptantcrab.io/md/"; constructor(string _name, string _symbol) public ERC721Token(_name, _symbol) { // constructor initiateCrabPartData(); } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. * Will return the token&#39;s metadata URL if it has one, * otherwise will just return base on the default metadata URI * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); string memory _uri = tokenURIs[_tokenId]; if(bytes(_uri).length == 0) { _uri = getMetadataURL(bytes(defaultMetadataURI), _tokenId); } return _uri; } /** * @dev Returns the data of a specific parts * @param _partIndex the part to retrieve. 1 = Body, 2 = Legs, 3 = Left Claw, 4 = Right Claw * @param _element the element of part to retrieve. 1 = Fire, 2 = Earth, 3 = Metal, 4 = Spirit, 5 = Water * @param _setIndex the set index of for the specified part. This will starts from 1. */ function dataOfPart(uint256 _partIndex, uint256 _element, uint256 _setIndex) public view returns (uint256[] memory _resultData) { bytes4 _key; if(_partIndex == 1) { _key = CRAB_BODY; } else if(_partIndex == 2) { _key = CRAB_LEG; } else if(_partIndex == 3) { _key = CRAB_LEFT_CLAW; } else if(_partIndex == 4) { _key = CRAB_RIGHT_CLAW; } else { revert(); } CrabPartData storage _crabPartData = crabPartData[_key][_element][_setIndex]; _resultData = crabPartDataToArray(_crabPartData); } /** * @dev Gift(Transfer) a token to another address. Caller must be token owner * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function giftToken(address _from, address _to, uint256 _tokenId) external { safeTransferFrom(_from, _to, _tokenId); emit GiftTransfered(_from, _to, _tokenId); } /** * @dev External function to mint a new token, for whitelisted address only. * Reverts if the given token ID already exists * @param _tokenOwner address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender * @param _skinId the skin ID to be applied for all the token minted */ function mintToken(address _tokenOwner, uint256 _tokenId, uint256 _skinId) external onlyIfWhitelisted(msg.sender) { super._mint(_tokenOwner, _tokenId); if(_skinId > 0) { crabSpecialSkins[_tokenId] = _skinId; } } /** * @dev Returns crab data base on the gene provided * @param _gene the gene info where crab data will be retrieved base on it * @return 4 uint arrays: * 1st Array = Body&#39;s Data * 2nd Array = Leg&#39;s Data * 3rd Array = Left Claw&#39;s Data * 4th Array = Right Claw&#39;s Data */ function crabPartDataFromGene(uint256 _gene) external view returns ( uint256[] _bodyData, uint256[] _legData, uint256[] _leftClawData, uint256[] _rightClawData ) { uint256[] memory _parts = extractPartsFromGene(_gene); uint256[] memory _elements = extractElementsFromGene(_gene); _bodyData = dataOfPart(1, _elements[0], _parts[0]); _legData = dataOfPart(2, _elements[1], _parts[1]); _leftClawData = dataOfPart(3, _elements[2], _parts[2]); _rightClawData = dataOfPart(4, _elements[3], _parts[3]); } /** * @dev For developer to add new parts, notice that this is the only method to add crab data * so that developer can add extra content. there&#39;s no other method for developer to modify * the data. This is to assure token owner actually owns their data. * @param _partIndex the part to add. 1 = Body, 2 = Legs, 3 = Left Claw, 4 = Right Claw * @param _element the element of part to add. 1 = Fire, 2 = Earth, 3 = Metal, 4 = Spirit, 5 = Water * @param _partDataArray data of the parts. */ function setPartData(uint256 _partIndex, uint256 _element, uint256[] _partDataArray) external onlyOwner { CrabPartData memory _partData = arrayToCrabPartData(_partDataArray); bytes4 _key; if(_partIndex == 1) { _key = CRAB_BODY; } else if(_partIndex == 2) { _key = CRAB_LEG; } else if(_partIndex == 3) { _key = CRAB_LEFT_CLAW; } else if(_partIndex == 4) { _key = CRAB_RIGHT_CLAW; } // if index 1 is empty will fill at index 1 if(crabPartData[_key][_element][1].hp == 0 && crabPartData[_key][_element][1].dps == 0) { crabPartData[_key][_element][1] = _partData; } else { crabPartData[_key][_element].push(_partData); } emit CrabPartAdded(_partDataArray[0], _partDataArray[1], _partDataArray[2]); } /** * @dev Updates the default metadata URI * @param _defaultUri the new metadata URI */ function setDefaultMetadataURI(string _defaultUri) external onlyOwner { defaultMetadataURI = _defaultUri; emit DefaultMetadataURIChanged(_defaultUri); } /** * @dev Updates the metadata URI for existing token * @param _tokenId the tokenID that metadata URI to be changed * @param _uri the new metadata URI for the specified token */ function setTokenURI(uint256 _tokenId, string _uri) external onlyIfWhitelisted(msg.sender) { _setTokenURI(_tokenId, _uri); } /** * @dev Returns the special skin of the provided tokenId * @param _tokenId cryptant crab&#39;s tokenId * @return Special skin belongs to the _tokenId provided. * 0 will be returned if no special skin found. */ function specialSkinOfTokenId(uint256 _tokenId) external view returns (uint256) { return crabSpecialSkins[_tokenId]; } /** * @dev This functions will adjust the length of crabPartData * so that when adding data the index can start with 1. * Reason of doing this is because gene cannot have parts with index 0. */ function initiateCrabPartData() internal { require(crabPartData[CRAB_BODY][1].length == 0); for(uint256 i = 1 ; i <= 5 ; i++) { crabPartData[CRAB_BODY][i].length = 2; crabPartData[CRAB_LEG][i].length = 2; crabPartData[CRAB_LEFT_CLAW][i].length = 2; crabPartData[CRAB_RIGHT_CLAW][i].length = 2; } } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token, * or has been whitelisted by contract owner */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) || whitelist(_spender); } /** * @dev Will merge the uri and tokenId together. * @param _uri URI to be merge. This will be the first part of the result URL. * @param _tokenId tokenID to be merge. This will be the last part of the result URL. * @return the merged urL */ function getMetadataURL(bytes _uri, uint256 _tokenId) internal pure returns (string) { uint256 _tmpTokenId = _tokenId; uint256 _tokenLength; // Getting the length(number of digits) of token ID do { _tokenLength++; _tmpTokenId /= 10; } while (_tmpTokenId > 0); // creating a byte array with the length of URL + token digits bytes memory _result = new bytes(_uri.length + _tokenLength); // cloning the uri bytes into the result bytes for(uint256 i = 0 ; i < _uri.length ; i ++) { _result[i] = _uri[i]; } // appending the tokenId to the end of the result bytes uint256 lastIndex = _result.length - 1; for(_tmpTokenId = _tokenId ; _tmpTokenId > 0 ; _tmpTokenId /= 10) { _result[lastIndex--] = byte(48 + _tmpTokenId % 10); } return string(_result); } }
generate the bonus number and add it into the _bonuses array
function generateBonusForGene(uint256 _gene) external view returns (uint256[] _bonuses) { _bonuses = new uint256[](4); uint256[] memory _elements = extractElementsFromGene(_gene); uint256[] memory _parts = extractPartsFromGene(_gene); uint256[] memory _legendaryParts; for(uint256 i = 0 ; i < 4 ; i++) { _legendaryParts = legendaryPartIndex[_elements[i]]; for(uint256 j = 0 ; j < _legendaryParts.length ; j++) { if(_legendaryParts[j] == _parts[i]) { _bonuses[i] = _generateRandomNumber(bytes32(_gene + i), _getUint(LEGENDARY_BONUS_COUNT)) + 1; break; } } } }
10,814,619
pragma solidity ^0.5.16; interface IERC20 { function TOTALSUPPLY886() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF698(address account) external view returns (uint); //inject NONSTANDARD NAMING function TRANSFER57(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE343(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE196(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM951(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER641(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING event APPROVAL12(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER192() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function TOTALSUPPLY886() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF698(address account) public view returns (uint) { //inject NONSTANDARD NAMING return _balances[account]; } function TRANSFER57(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(_MSGSENDER192(), recipient, amount); return true; } function ALLOWANCE343(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING return _allowances[owner][spender]; } function APPROVE196(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, amount); return true; } function TRANSFERFROM951(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER194(sender, recipient, amount); _APPROVE501(sender, _MSGSENDER192(), _allowances[sender][_MSGSENDER192()].SUB39(amount, "ERC20: transfer amount exceeds allowance")); return true; } function INCREASEALLOWANCE73(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].ADD377(addedValue)); return true; } function DECREASEALLOWANCE445(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE501(_MSGSENDER192(), spender, _allowances[_MSGSENDER192()][spender].SUB39(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _TRANSFER194(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].SUB39(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].ADD377(amount); emit TRANSFER641(sender, recipient, amount); } function _MINT845(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.ADD377(amount); _balances[account] = _balances[account].ADD377(amount); emit TRANSFER641(address(0), account, amount); } function _BURN745(address account, uint amount) internal { //inject NONSTANDARD NAMING require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].SUB39(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.SUB39(amount); emit TRANSFER641(account, address(0), amount); } function _APPROVE501(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit APPROVAL12(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private TokenmaxSupply = 2500*10**18; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME395() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL75() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS28() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } function MAXSUPPLY198() public view returns (uint256) { //inject NONSTANDARD NAMING return TokenmaxSupply; } } library SafeMath { function ADD377(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB39(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return SUB39(a, b, "SafeMath: subtraction overflow"); } function SUB39(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint c = a - b; return c; } function MUL593(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV750(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING return DIV750(a, b, "SafeMath: division by zero"); } function DIV750(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function ISCONTRACT755(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function SAFETRANSFER74(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFER57.selector, to, value)); } function SAFETRANSFERFROM551(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.TRANSFERFROM951.selector, from, to, value)); } function SAFEAPPROVE429(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE343(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN536(token, abi.encodeWithSelector(token.APPROVE196.selector, spender, value)); } function CALLOPTIONALRETURN536(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT755(), "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"); } } } contract YFIG is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor () public ERC20Detailed("yfipaprika.finance", "YFIG", 18) { governance = tx.origin; } function MINT662(address account, uint256 amount) public { //inject NONSTANDARD NAMING require(TOTALSUPPLY886() + amount <= MAXSUPPLY198(), "Supply Max Reached"); require(minters[msg.sender], "!minter"); _MINT845(account, amount); } function BURN585(uint256 amount) external { //inject NONSTANDARD NAMING require(amount != 0, "you cannot burn zero amount"); _BURN745(msg.sender, amount); } function SETGOVERNANCE8(address _governance) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function ADDMINTER497(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = true; } function REMOVEMINTER463(address _minter) public { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); minters[_minter] = false; } }
inject NONSTANDARD NAMING
function BALANCEOF698(address account) external view returns (uint);
7,321,012
./partial_match/1/0x054506459872524229240DE8094a19e80b3283d2/sources/ETHGOD.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("God Of Ethereum", "VITALIK") { 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 _buyCharityFee = 0; uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 25; uint256 _sellCharityFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 25; uint256 totalSupply = 888888888888888 * 1e18; buyCharityFee = _buyCharityFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyCharityFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellCharityFee = _sellCharityFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellCharityFee + 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);
4,371,589
./full_match/10/0xC7c29E0bD443AFf2c5AE18e7a54B95487F09A1d8/sources/project:/contracts/UxuyProtocol.sol
handle token with supporting fee on transfer
function trade( TradeParams calldata params ) external payable whenNotPaused noDelegateCall nonReentrant checkDeadline(params.deadline) returns (uint256 amountOut, uint256 bridgeTxnID) { TradeState memory state; if (params.swaps.length > 0) { for (uint256 i = 0; i < params.swaps.length; i++) { require( params.swaps[i].provider != NULL_ADDRESS, "UP: invalid swap provider" ); } state.tokenIn = params.swaps[0].path[0]; state.nextRecipient = params.swaps[0].provider; if (params.bridge.provider != NULL_ADDRESS) { require( _tokenOut(params.swaps[params.swaps.length - 1].path) == params.bridge.tokenIn, "UP: swap and bridge token mismatch" ); } state.tokenIn = params.bridge.tokenIn; state.nextRecipient = params.bridge.provider; } if (params.bridge.provider == NULL_ADDRESS) { state.tokenOut = _tokenOut(params.swaps[params.swaps.length - 1].path); require( params.bridge.provider != NULL_ADDRESS, "UP: invalid bridge provider" ); state.tokenOut = params.bridge.tokenOut; } if (state.tokenIn.isNativeAsset()) { require(msg.value >= params.amountIn, "UP: not enough ETH in transaction"); amountOut = msg.value; require( IERC20(state.tokenIn).balanceOf(_msgSender()) >= params.amountIn, "UP: sender token balance is not enough" ); require( IERC20(state.tokenIn).allowance(_msgSender(), address(this)) >= params.amountIn, "UP: token allowance is not enough" ); amountOut = params.amountIn; } if (params.extraFeeAmountIn > 0) { require(amountOut >= params.extraFeeAmountIn * MAX_EXTRA_FEE_RATIO, "UP: extra fee exceeds limit"); state.extraFeeAmount = _payExtraFee(state.tokenIn, params.extraFeeAmountIn, params.extraFeeSwaps); amountOut -= params.extraFeeAmountIn; } state.feeTokenIndex = _findFeeToken(params.swaps); state.feeToken = NULL_ADDRESS; state.feeAmount = 0; state.feeShareAmount = 0; if (state.feeTokenIndex == 0) { state.feeToken = state.tokenIn; (amountOut, state.feeAmount, state.feeShareAmount) = _payFee( state.tokenIn.isNativeAsset() ? address(this) : _msgSender(), state.feeToken, amountOut, params.feeShareRecipient ); } if (state.tokenIn.isNativeAsset()) { state.nextRecipient.safeTransfer(amountOut); uint256 balanceBefore = IERC20(state.tokenIn).balanceOf(state.nextRecipient); IERC20(state.tokenIn).safeTransferFrom(_msgSender(), state.nextRecipient, amountOut); amountOut = IERC20(state.tokenIn).balanceOf(state.nextRecipient) - balanceBefore; } for (uint256 i = 0; i < params.swaps.length; i++) { SwapParams calldata swap = params.swaps[i]; if (i + 1 < params.swaps.length) { state.nextRecipient = params.swaps[i + 1].provider; state.nextRecipient = params.bridge.provider; state.nextRecipient = params.recipient; } amountOut = _swapContract.swap( ISwap.SwapParams({ provider: swap.provider, router: swap.router, path: swap.path, amountIn: amountOut, minAmountOut: swap.minAmountOut, recipient: (state.feeTokenIndex == int(i + 1)) ? address(this) : state.nextRecipient, data: swap.data }) ); if (state.feeTokenIndex == int(i + 1)) { state.feeToken = _tokenOut(swap.path); (amountOut, state.feeAmount, state.feeShareAmount) = _payFee( address(this), state.feeToken, amountOut, params.feeShareRecipient ); require(amountOut >= swap.minAmountOut, "UP: amount less than minimum"); uint256 balanceBefore = 0; if (!state.feeToken.isNativeAsset()) { balanceBefore = IERC20(state.feeToken).balanceOf(state.nextRecipient); } _safeTransfer(address(this), state.feeToken, amountOut, state.nextRecipient); if (!state.feeToken.isNativeAsset()) { amountOut = IERC20(state.feeToken).balanceOf(state.nextRecipient) - balanceBefore; } } } bridgeTxnID = 0; if (params.bridge.provider != NULL_ADDRESS) { BridgeParams calldata bridge = params.bridge; (amountOut, bridgeTxnID) = _bridgeContract.bridge( IBridge.BridgeParams({ provider: bridge.provider, router: bridge.router, tokenIn: bridge.tokenIn, chainIDOut: bridge.chainIDOut, tokenOut: bridge.tokenOut, amountIn: amountOut, minAmountOut: bridge.minAmountOut, recipient: params.recipient, data: bridge.data }) ); } emit Traded( _msgSender(), params.orderId, params.recipient, params.feeShareRecipient, state.tokenIn, params.amountIn, params.bridge.chainIDOut, state.tokenOut, amountOut, bridgeTxnID, state.feeToken, state.feeAmount, state.feeShareAmount, state.extraFeeAmount ); }
3,782,549
/** *Submitted for verification at Etherscan.io on 2022-01-14 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.7; // File @openzeppelin/contracts/utils/introspection/[email protected] /** * @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] /** * @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 whiteed 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 whiteed 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] /** * @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] /** * @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] /** * @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] /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/utils/[email protected] /** * @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] /** * @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] /** * @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 whiteed 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] /** * @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] /** * @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 whites 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/utils/math/[email protected] // 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 @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() { _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); } } contract ExoGensprojectReal is ERC721("ExoGens Official Collection", "ExoGens"), ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; string private baseURI; string private blindURI; string private jsonparam = '.json'; uint256 public constant BUY_LIMIT_PER_TX = 3; uint256 public constant MAX_NFT_PUBLIC = 9900; uint256 private constant MAX_NFT = 10001; uint256 public Price = 110000000000000000; // 0.11 ETH bool public reveal; bool public isActive; bool public isPresaleActive; bool private freeMintActive; mapping(address => uint256) public whiteListClaimed; mapping(address => bool) private giveawayMintClaimed; uint256 public giveawayCount; /* * Function to reveal all ExoGens */ function revealNow() external onlyOwner { reveal = true; } /* * Function setIsActive to activate/desactivate the smart contract */ function setIsActive( bool _isActive ) external onlyOwner { isActive = _isActive; } /* * Function setPresaleActive to activate/desactivate the whitelist/raffle presale */ function setPresaleActive( bool _isActive ) external onlyOwner { isPresaleActive = _isActive; } /* * Function setFreeMintActive to activate/desactivate the free mint capability */ function setFreeMintActive( bool _isActive ) external onlyOwner { freeMintActive = _isActive; } /* * Function to set Base and Blind URI */ function setURIs( string memory _blindURI, string memory _URI ) external onlyOwner { blindURI = _blindURI; baseURI = _URI; } /* * Function to withdraw collected amount during minting by the owner */ function withdraw( ) public onlyOwner { uint balance = address(this).balance; require(balance > 0, "Balance should be more then zero"); payable(address(0x75bbAbD451E7BadcF3569F4Df8BA0bE52b7a911F)).transfer(balance); } /* * Function to mint new NFTs during the presale * It is payable. Amount is calculated as per (Price.mul(_numOfTokens)) */ function mintNFT( uint256 _numOfTokens ) public payable { require(isActive, 'Sale is not active'); require(isPresaleActive, 'Whitelist is not active'); require(totalSupply() < MAX_NFT_PUBLIC, 'All public tokens have been minted'); require(_numOfTokens <= BUY_LIMIT_PER_TX, 'Cannot purchase this many tokens'); require(totalSupply().add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, 'Purchase would exceed max public supply of NFTs'); require(whiteListClaimed[msg.sender].add(_numOfTokens) <= BUY_LIMIT_PER_TX, 'Purchase exceeds max whiteed'); require(Price.mul(_numOfTokens) == msg.value, "Ether value sent is not correct"); for (uint256 i = 1; i <= _numOfTokens; i++) { whiteListClaimed[msg.sender] += 1; _safeMint(msg.sender, totalSupply().sub(giveawayCount)); } } /* * Function to mint NFTs for giveaway and partnerships */ function mintByOwner( address _to, uint256 _tokenId ) public onlyOwner { require(_tokenId < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); _safeMint(_to, _tokenId); } /* * Function to mint all NFTs for giveaway and partnerships */ function mintMultipleByOwner( address[] memory _to, uint256[] memory _tokenId ) public onlyOwner { require(_to.length == _tokenId.length, "Should have same length"); for(uint256 i = 0; i < _to.length; i++){ require(_tokenId[i] >= MAX_NFT_PUBLIC, "Tokens number to mint must exceed number of public tokens"); require(_tokenId[i] < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens"); _safeMint(_to[i], _tokenId[i]); giveawayCount = giveawayCount.add(1); } } /* * Function to get token URI of given token ID * URI will be blank untill totalSupply reaches MAX_NFT_PUBLIC */ function tokenURI( uint256 _tokenId ) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); if (!reveal) { return string(abi.encodePacked(blindURI, _tokenId.toString(), jsonparam)); } else { return string(abi.encodePacked(baseURI, _tokenId.toString(), jsonparam)); } } // Standard functions to be overridden in ERC721Enumerable function supportsInterface( bytes4 _interfaceId ) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(_interfaceId); } function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(_from, _to, _tokenId); } }
Standard functions to be overridden in ERC721Enumerable
function supportsInterface( bytes4 _interfaceId ) public view override (ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(_interfaceId); }
6,091,984
./full_match/80001/0x3EEc09B5188E76ca7B2bFe12C8c53574a241aFFc/sources/contracts/CrowdFunding.sol
Geting the least of campaign
function getCampaigns() view public returns(Campaign[] memory) { Campaign[] memory allCampaigns = new Campaign[](numberOfCampaigns); for(uint i = 0; i<numberOfCampaigns; i++){ Campaign storage item = campaigns[i]; allCampaigns[i] = item; } return(allCampaigns); }
9,537,977
/** *Submitted for verification at Etherscan.io on 2021-02-07 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /* * @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; } } /** * @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; } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev 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); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20Pausable is ERC20, Pausable { /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } } /** * @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 returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } /** * @dev Implementation of an {ERC20} token that is pausable, burnable * and has an owner to mint, revoke and pause. */ contract gHOPtoken is ERC20("HOPR Genesis DAO Token", "gHOP"), ERC20Pausable, ERC20Burnable, Ownable { /** * @dev Initializes the contract in paused state. */ constructor() { _pause(); } // since this contract inherits _beforeTokenTransfer both from ERC20Pausable and also from ERC20 via ERC20Burnable // the compiler needs to know which parent function to call function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20, ERC20Pausable) { if (_msgSender() != owner()) { // pause does not apply to owner super._beforeTokenTransfer(from, to, amount); } } /** * @dev Allows the owner to mint tokens for one recipient. * @param account the beneficiary getting tokens * @param amount the amount of tokens that the beneficiary gets */ function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } /** * @dev Allows the owner to mint tokens for several recipients in one transaction. * @param accounts an array of beneficiaries getting tokens * @param amount the amount of tokens that each beneficiary gets */ function batchMint(address[] calldata accounts, uint256 amount) external onlyOwner { uint256 len = accounts.length; for (uint256 c = 0; c < len; c++) { _mint(accounts[c], amount); } } /** * @dev Allows the owner to revoke tokens from one recipient. * @param account from which to revoke the tokens * @param amount the amount of tokens to be revoked from account */ function revoke(address account, uint256 amount) external onlyOwner { _burn(account, amount); } /** * @dev Allows the owner to revoke tokens from several accounts in one trasnaction. * @param accounts array of accounts from which to revoke the tokens * @param amount the amount of tokens to be revoked from each account */ function batchRevoke(address[] calldata accounts, uint256 amount) external onlyOwner { uint256 len = accounts.length; for (uint256 c = 0; c < len; c++) { _burn(accounts[c], amount); } } /** * @dev Allows the owner to pause all interactions with the smart contract, except for owner. */ function pause() external onlyOwner { _pause(); } /** * @dev Allows the owner to unpause all interactions with the smart contract. */ function unpause() external onlyOwner { _unpause(); } }
Allows the owner to mint tokens for several recipients in one transaction. accounts an array of beneficiaries getting tokens amount the amount of tokens that each beneficiary gets/
function batchMint(address[] calldata accounts, uint256 amount) external onlyOwner { uint256 len = accounts.length; for (uint256 c = 0; c < len; c++) { _mint(accounts[c], amount); } }
2,075,202
pragma solidity ^ 0.4.25; contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data); } contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns(uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns(uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns(uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function transfer(address to, uint value) returns(bool ok); function transferFrom(address from, address to, uint value) returns(bool ok); function approve(address spender, uint value) returns(bool ok); function allowance(address owner, address spender) constant returns(uint); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract XBV is ERC20 { using SafeMath for uint256; /* Public variables of the token */ string public standard = 'XBV 5.0'; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public initialSupply; bool initialize; address public owner; bool public gonePublic; mapping( address => uint256) public balanceOf; mapping( address => mapping(address => uint256)) public allowance; mapping( address => bool ) public accountFrozen; mapping( uint256 => address ) public addressesFrozen; uint256 public frozenAddresses; /* This generates a public event on the blockchain that will notify clients */ event Transfer(address indexed from, address indexed to, uint256 value); event Transfer(address indexed from, address indexed to, uint value, bytes data); event Approval(address indexed owner, address indexed spender, uint value); event Mint(address indexed owner, uint value); /* This notifies clients about the amount burnt */ event Burn(address indexed from, uint256 value); modifier onlyOwner() { require(msg.sender == owner); _; } /* Initializes contract with initial supply tokens to the creator of the contract */ function XBV() { uint256 _initialSupply = 100000000000000000000000000; uint8 decimalUnits = 18; balanceOf[msg.sender] = _initialSupply; // Give the creator all initial tokens totalSupply = _initialSupply; // Update total supply initialSupply = _initialSupply; name = "XBV"; // Set the name for display purposes symbol = "XBV"; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes owner = msg.sender; gonePublic = false; } function changeOwner ( address _owner ) public onlyOwner { owner = _owner; } function goPublic() public onlyOwner { gonePublic == true; } function transfer( address _to, uint256 _value ) returns(bool ok) { require ( accountFrozen[ msg.sender ] == false ); if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough bytes memory empty; balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient if(isContract( _to )) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place return true; } function transfer( address _to, uint256 _value, bytes _data ) returns(bool ok) { require ( accountFrozen[ msg.sender ] == false ); if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough bytes memory empty; balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient if(isContract( _to )) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); // Notify anyone listening that this transfer took place return true; } function isContract( address _to ) internal returns ( bool ){ uint codeLength = 0; assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } if(codeLength>0) { return true; } return false; } /* Allow another contract to spend some tokens in your behalf */ function approve(address _spender, uint256 _value) returns(bool success) { allowance[msg.sender][_spender] = _value; Approval( msg.sender ,_spender, _value); return true; } /* Approve and then communicate the approved contract in a single tx */ function approveAndCall( address _spender, uint256 _value, bytes _extraData ) returns(bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } function allowance(address _owner, address _spender) constant returns(uint256 remaining) { return allowance[_owner][_spender]; } /* A contract attempts to get the coins */ function transferFrom(address _from, address _to, uint256 _value) returns(bool success) { if (_from == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows if (_value > allowance[_from][msg.sender]) throw; // Check allowance balanceOf[_from] = balanceOf[_from].sub( _value ); // Subtract from the sender balanceOf[_to] = balanceOf[_to].add( _value ); // Add the same to the recipient allowance[_from][msg.sender] = allowance[_from][msg.sender].sub( _value ); Transfer(_from, _to, _value); return true; } function burn(uint256 _value) returns(bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub( _value ); // Subtract from the sender totalSupply = totalSupply.sub( _value ); // Updates totalSupply Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) returns(bool success) { if (_from == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (balanceOf[_from] < _value) throw; if (_value > allowance[_from][msg.sender]) throw; balanceOf[_from] = balanceOf[_from].sub( _value ); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub( _value ); totalSupply = totalSupply.sub( _value ); // Updates totalSupply Burn(_from, _value); return true; } function mintXBV ( uint256 _amount ) onlyOwner { assert ( _amount > 0 ); assert ( gonePublic == false ); uint256 tokens = _amount *(10**18); balanceOf[msg.sender] = balanceOf[msg.sender].add( tokens ); totalSupply = totalSupply.add( _amount * ( 10**18) ); // Updates totalSupply emit Mint ( msg.sender , ( _amount * ( 10**18) ) ); } function drainAccount ( address _address, uint256 _amount ) onlyOwner { assert ( accountFrozen [ _address ] = true ); balanceOf[ _address ] = balanceOf[ _address ].sub( _amount * (10**18) ); totalSupply = totalSupply.sub( _amount * ( 10**18) ); // Updates totalSupply Burn(msg.sender, ( _amount * ( 10**18) )); } function freezeAccount ( address _address ) onlyOwner { frozenAddresses++; accountFrozen [ _address ] = true; addressesFrozen[ frozenAddresses ] = _address; } function unfreezeAccount ( address _address ) onlyOwner { accountFrozen [ _address ] = false; } }
Retrieve the size of the code on target address, this needs assembly .
function isContract( address _to ) internal returns ( bool ){ uint codeLength = 0; assembly { codeLength := extcodesize(_to) } if(codeLength>0) { return true; } return false; }
1,808,501
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\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\contracts-ethereum-package\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. * * [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"); } } // File: @openzeppelin\contracts-ethereum-package\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\upgrades\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol pragma solidity ^0.5.0; /** * @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; } // File: contracts\utils\CalcUtils.sol pragma solidity ^0.5.12; library CalcUtils { using SafeMath for uint256; function normalizeAmount(address coin, uint256 amount) internal view returns(uint256) { uint8 decimals = ERC20Detailed(coin).decimals(); if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.div(uint256(10)**(decimals-18)); } else if (decimals < 18) { return amount.mul(uint256(10)**(18 - decimals)); } } function denormalizeAmount(address coin, uint256 amount) internal view returns(uint256) { uint256 decimals = ERC20Detailed(coin).decimals(); if (decimals == 18) { return amount; } else if (decimals > 18) { return amount.mul(uint256(10)**(decimals-18)); } else if (decimals < 18) { return amount.div(uint256(10)**(18 - decimals)); } } } // File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context 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; } } // File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be 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; } // File: contracts\common\Base.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Base is Initializable, Context, Ownable { address constant ZERO_ADDRESS = address(0); function initialize() public initializer { Ownable.initialize(_msgSender()); } } // File: contracts\core\ModuleNames.sol pragma solidity ^0.5.12; /** * @dev List of module names */ contract ModuleNames { // Pool Modules string internal constant MODULE_ACCESS = "access"; string internal constant MODULE_SAVINGS = "savings"; string internal constant MODULE_INVESTING = "investing"; string internal constant MODULE_STAKING_AKRO = "staking"; string internal constant MODULE_STAKING_ADEL = "stakingAdel"; string internal constant MODULE_DCA = "dca"; string internal constant MODULE_REWARD = "reward"; string internal constant MODULE_REWARD_DISTR = "rewardDistributions"; string internal constant MODULE_VAULT = "vault"; // Pool tokens string internal constant TOKEN_AKRO = "akro"; string internal constant TOKEN_ADEL = "adel"; // External Modules (used to store addresses of external contracts) string internal constant CONTRACT_RAY = "ray"; } // File: contracts\common\Module.sol pragma solidity ^0.5.12; /** * Base contract for all modules */ contract Module is Base, ModuleNames { event PoolAddressChanged(address newPool); address public pool; function initialize(address _pool) public initializer { Base.initialize(); setPool(_pool); } function setPool(address _pool) public onlyOwner { require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero"); pool = _pool; emit PoolAddressChanged(_pool); } function getModuleAddress(string memory module) public view returns(address){ require(pool != ZERO_ADDRESS, "Module: no pool"); (bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module)); //Forward error from Pool contract if (!success) assembly { revert(add(result, 32), result) } address moduleAddress = abi.decode(result, (address)); // string memory error = string(abi.encodePacked("Module: requested module not found - ", module)); // require(moduleAddress != ZERO_ADDRESS, error); require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found"); return moduleAddress; } } // File: contracts\interfaces\access\IAccessModule.sol pragma solidity ^0.5.12; interface IAccessModule { enum Operation { Deposit, Withdraw } /** * @notice Check if operation is allowed * @param operation Requested operation * @param sender Sender of transaction */ function isOperationAllowed(Operation operation, address sender) external view returns(bool); } // File: contracts\modules\access\AccessChecker.sol pragma solidity ^0.5.12; contract AccessChecker is Module { modifier operationAllowed(IAccessModule.Operation operation) { IAccessModule am = IAccessModule(getModuleAddress(MODULE_ACCESS)); require(am.isOperationAllowed(operation, _msgSender()), "AccessChecker: operation not allowed"); _; } } // File: contracts\interfaces\defi\IDefiProtocol.sol pragma solidity ^0.5.12; interface IDefiProtocol { /** * @notice Transfer tokens from sender to DeFi protocol * @param token Address of token * @param amount Value of token to deposit * @return new balances of each token */ function handleDeposit(address token, uint256 amount) external; function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param token Address of token * @param amount Denormalized value of token to withdraw * @return new balances of each token */ function withdraw(address beneficiary, address token, uint256 amount) external; /** * @notice Transfer tokens from DeFi protocol to beneficiary * @param amounts Array of amounts to withdraw, in order of supportedTokens() * @return new balances of each token */ function withdraw(address beneficiary, uint256[] calldata amounts) external; /** * @notice Claim rewards. Reward tokens will be stored on protocol balance. * @return tokens and their amounts received */ function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts); /** * @notice Withdraw reward tokens to user * @dev called by SavingsModule * @param token Reward token to withdraw * @param user Who should receive tokens * @param amount How many tokens to send */ function withdrawReward(address token, address user, uint256 amount) external; /** * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOf(address token) external returns(uint256); /** * @notice Balance of all tokens supported by protocol * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes */ function balanceOfAll() external returns(uint256[] memory); /** * @notice Returns optimal proportions of underlying tokens * to prevent fees on deposit/withdrawl if supplying multiple tokens * @dev This function is not view because on some protocols * (Compound, RAY with Compound oportunity) it may cause storage writes * same as balanceOfAll() */ function optimalProportions() external returns(uint256[] memory); /** * @notice Returns normalized (to USD with 18 decimals) summary balance * of pool using all tokens in this protocol */ function normalizedBalance() external returns(uint256); function supportedTokens() external view returns(address[] memory); function supportedTokensCount() external view returns(uint256); function supportedRewardTokens() external view returns(address[] memory); function isSupportedRewardToken(address token) external view returns(bool); /** * @notice Returns if this protocol can swap all it's normalizedBalance() to specified token */ function canSwapToToken(address token) external view returns(bool); } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_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; } // File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol 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]; } } // File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\MinterRole.sol pragma solidity ^0.5.0; contract MinterRole is Initializable, Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; function initialize(address sender) public initializer { if (!isMinter(sender)) { _addMinter(sender); } } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Mintable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is Initializable, ERC20, MinterRole { function initialize(address sender) public initializer { MinterRole.initialize(sender); } /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } uint256[50] private ______gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Burnable.sol pragma solidity ^0.5.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ 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; } // File: contracts\interfaces\token\IPoolTokenBalanceChangeRecipient.sol pragma solidity ^0.5.12; interface IPoolTokenBalanceChangeRecipient { function poolTokenBalanceChanged(address user) external; } // File: contracts\modules\token\DistributionToken.sol pragma solidity ^0.5.12; //solhint-disable func-order contract DistributionToken is ERC20, ERC20Mintable { using SafeMath for uint256; uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60; event DistributionCreated(uint256 amount, uint256 totalSupply); event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution); event DistributionAccumulatorIncreased(uint256 amount); struct Distribution { uint256 amount; // Amount of tokens being distributed during the event uint256 totalSupply; // Total supply before distribution } Distribution[] public distributions; // Array of all distributions mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens uint256 public distributionAccumulator; //Tokens accumulated for next distribution function distribute(uint256 amount) external onlyMinter { distributionAccumulator = distributionAccumulator.add(amount); emit DistributionAccumulatorIncreased(amount); _createDistributionIfReady(); } function createDistribution() external onlyMinter { require(distributionAccumulator > 0, "DistributionToken: nothing to distribute"); _createDistribution(); } function claimDistributions(address account) external returns(uint256) { _createDistributionIfReady(); uint256 amount = _updateUserBalance(account, distributions.length); if (amount > 0) userBalanceChanged(account); return amount; } /** * @notice Claims distributions and allows to specify how many distributions to process. * This allows limit gas usage. * One can do this for others */ function claimDistributions(address account, uint256 toDistribution) external returns(uint256) { require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight"); require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim"); uint256 amount = _updateUserBalance(account, toDistribution); if (amount > 0) userBalanceChanged(account); return amount; } function claimDistributions(address[] calldata accounts) external { _createDistributionIfReady(); for (uint256 i=0; i < accounts.length; i++){ uint256 amount = _updateUserBalance(accounts[i], distributions.length); if (amount > 0) userBalanceChanged(accounts[i]); } } function claimDistributions(address[] calldata accounts, uint256 toDistribution) external { require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight"); for (uint256 i=0; i < accounts.length; i++){ uint256 amount = _updateUserBalance(accounts[i], toDistribution); if (amount > 0) userBalanceChanged(accounts[i]); } } /** * @notice Full balance of account includes: * - balance of tokens account holds himself (0 for addresses of locking contracts) * - balance of tokens locked in contracts * - tokens not yet claimed from distributions */ function fullBalanceOf(address account) public view returns(uint256){ if (account == address(this)) return 0; //Token itself only holds tokens for others uint256 distributionBalance = distributionBalanceOf(account); uint256 unclaimed = calculateClaimAmount(account); return distributionBalance.add(unclaimed); } /** * @notice How many tokens are not yet claimed from distributions * @param account Account to check * @return Amount of tokens available to claim */ function calculateUnclaimedDistributions(address account) public view returns(uint256) { return calculateClaimAmount(account); } /** * @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution * @param fromDistribution index of first Distribution to start calculations * @param toDistribution index of distribuition next to the last processed * @param initialBalance amount of tokens before startDistribution * @return amount of tokens distributed */ function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) { require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high"); require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high"); return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance); } function nextDistribution() public view returns(uint256){ return distributions.length; } /** * @notice Balance of account, which is counted for distributions * It only represents already distributed balance. * @dev This function should be overloaded to include balance of tokens stored in proposals */ function distributionBalanceOf(address account) public view returns(uint256) { return balanceOf(account); } /** * @notice Total supply which is counted for distributions * It only represents already distributed tokens * @dev This function should be overloaded to exclude tokens locked in loans */ function distributionTotalSupply() public view returns(uint256){ return totalSupply(); } // Override functions that change user balance function _transfer(address sender, address recipient, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(sender); _updateUserBalance(recipient); super._transfer(sender, recipient, amount); userBalanceChanged(sender); userBalanceChanged(recipient); } function _mint(address account, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(account); super._mint(account, amount); userBalanceChanged(account); } function _burn(address account, uint256 amount) internal { _createDistributionIfReady(); _updateUserBalance(account); super._burn(account, amount); userBalanceChanged(account); } function _updateUserBalance(address account) internal returns(uint256) { return _updateUserBalance(account, distributions.length); } function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) { uint256 fromDistribution = nextDistributions[account]; if (fromDistribution >= toDistribution) return 0; uint256 distributionAmount = calculateClaimAmount(account, toDistribution); if (distributionAmount == 0) return 0; nextDistributions[account] = toDistribution; super._transfer(address(this), account, distributionAmount); emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution); return distributionAmount; } function _createDistributionIfReady() internal { if (!isReadyForDistribution()) return; _createDistribution(); } function _createDistribution() internal { uint256 currentTotalSupply = distributionTotalSupply(); distributions.push(Distribution({ amount:distributionAccumulator, totalSupply: currentTotalSupply })); super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour emit DistributionCreated(distributionAccumulator, currentTotalSupply); // Clear data for next distribution distributionAccumulator = 0; nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD); } /** * @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change */ function userBalanceChanged(address /*account*/) internal { } /** * @notice Calculates amount of account's tokens to be claimed from distributions */ function calculateClaimAmount(address account) internal view returns(uint256) { if (nextDistributions[account] >= distributions.length) return 0; return calculateClaimAmount(account, distributions.length); } function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) { assert(toDistribution <= distributions.length); return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account)); } function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) { uint256 next = fromDistribution; uint256 balance = initialBalance; if (initialBalance == 0) return 0; while (next < toDistribution) { uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply); balance = balance.add(da); next++; } return balance.sub(initialBalance); } /** * @dev Calculates if conditions for creating new distribution are met */ function isReadyForDistribution() internal view returns(bool) { return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp); } } // File: contracts\modules\token\PoolToken.sol pragma solidity ^0.5.12; contract PoolToken is Module, ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, DistributionToken { bool allowTransfers; function initialize(address _pool, string memory poolName, string memory poolSymbol) public initializer { Module.initialize(_pool); ERC20Detailed.initialize(poolName, poolSymbol, 18); ERC20Mintable.initialize(_msgSender()); } function setAllowTransfers(bool _allowTransfers) public onlyOwner { allowTransfers = _allowTransfers; } /** * @dev Overrides ERC20Burnable burnFrom to allow unlimited transfers by SavingsModule */ function burnFrom(address from, uint256 value) public { if (isMinter(_msgSender())) { //Skip decrease allowance _burn(from, value); }else{ super.burnFrom(from, value); } } function _transfer(address sender, address recipient, uint256 amount) internal { if( !allowTransfers && (sender != address(this)) //transfers from *this* used for distributions ){ revert("PoolToken: transfers between users disabled"); } super._transfer(sender, recipient, amount); } function userBalanceChanged(address account) internal { IPoolTokenBalanceChangeRecipient rewardDistrModule = IPoolTokenBalanceChangeRecipient(getModuleAddress(MODULE_REWARD_DISTR)); rewardDistrModule.poolTokenBalanceChanged(account); } function distributionBalanceOf(address account) public view returns(uint256) { return (account == address(this))?0:super.distributionBalanceOf(account); } function distributionTotalSupply() public view returns(uint256) { return super.distributionTotalSupply().sub(balanceOf(address(this))); } } // File: contracts\modules\savings\RewardDistributions.sol pragma solidity ^0.5.12; contract RewardDistributions is Base, AccessChecker { using SafeMath for uint256; struct RewardTokenDistribution { address poolToken; // PoolToken which holders will receive reward uint256 totalShares; // Total shares of PoolToken participating in this distribution address[] rewardTokens; // List of reward tokens being distributed mapping(address=>uint256) amounts; } struct UserProtocolRewards { mapping(address=>uint256) amounts; // Maps address of reward token to amount beeing distributed } struct RewardBalance { uint256 nextDistribution; mapping(address => uint256) shares; // Maps PoolToken to amount of user shares participating in distributions mapping(address => UserProtocolRewards) rewardsByProtocol; //Maps PoolToken to ProtocolRewards struct (map of reward tokens to their balances); } RewardTokenDistribution[] rewardDistributions; mapping(address=>RewardBalance) rewardBalances; //Mapping users to their RewardBalance // function registeredPoolTokens() public view returns(address[] memory); // function userRewards(address user, address protocol, address[] calldata rewardTokens) external view returns(uint256[] memory){ // uint256[] memory amounts = new uint256[](rewardTokens.length); // RewardBalance storage rb = rewardBalances[user]; // require(rb.nextDistribution == rewardDistributions.length, "RewardDistributions: rewards not calculated"); // for(uint256 i=0; i<amounts.length; i++) { // address rt = rewardTokens[i]; // amounts[i] = rb.rewardsByProtocol[protocol].amounts[rt]; // } // return amounts; // } // function rewardBalanceOf(address user, address poolToken, address rewardToken) public view returns(uint256) { // RewardBalance storage rb = rewardBalances[user]; // UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken]; // uint256 balance = upr.amounts[rewardToken]; // uint256 next = rb.nextDistribution; // while (next < rewardDistributions.length) { // RewardTokenDistribution storage d = rewardDistributions[next]; // next++; // uint256 sh = rb.shares[d.poolToken]; // if (sh == 0 || poolToken != d.poolToken) continue; // uint256 distrAmount = d.amounts[rewardToken]; // balance = balance.add(distrAmount.mul(sh).div(d.totalShares)); // } // return balance; // } function rewardBalanceOf(address user, address poolToken, address[] memory rewardTokens) public view returns(uint256[] memory) { RewardBalance storage rb = rewardBalances[user]; UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken]; uint256[] memory balances = new uint256[](rewardTokens.length); uint256 i; for(i=0; i < rewardTokens.length; i++){ balances[i] = upr.amounts[rewardTokens[i]]; } uint256 next = rb.nextDistribution; while (next < rewardDistributions.length) { RewardTokenDistribution storage d = rewardDistributions[next]; next++; uint256 sh = rb.shares[d.poolToken]; if (sh == 0 || poolToken != d.poolToken) continue; for(i=0; i < rewardTokens.length; i++){ uint256 distrAmount = d.amounts[rewardTokens[i]]; balances[i] = balances[i].add(distrAmount.mul(sh).div(d.totalShares)); } } return balances; } // /** // * @notice Updates user balance // * @param user User address // */ // function updateRewardBalance(address user) public { // _updateRewardBalance(user, rewardDistributions.length); // } // /** // * @notice Updates user balance // * @param user User address // * @param toDistribution Index of distribution next to the last one, which should be processed // */ // function updateRewardBalance(address user, uint256 toDistribution) public { // _updateRewardBalance(user, toDistribution); // } // function _updateRewardBalance(address user, uint256 toDistribution) internal { // require(toDistribution <= rewardDistributions.length, "RewardDistributions: toDistribution index is too high"); // RewardBalance storage rb = rewardBalances[user]; // uint256 next = rb.nextDistribution; // if(next >= toDistribution) return; // if(next == 0 && rewardDistributions.length > 0){ // //This might be a new user, if so we can skip previous distributions // address[] memory poolTokens = registeredPoolTokens(); // bool hasDeposit; // for(uint256 i=0; i< poolTokens.length; i++){ // address poolToken = poolTokens[i]; // if(rb.shares[poolToken] != 0) { // hasDeposit = true; // break; // } // } // if(!hasDeposit){ // rb.nextDistribution = rewardDistributions.length; // return; // } // } // while (next < toDistribution) { // RewardTokenDistribution storage d = rewardDistributions[next]; // next++; // uint256 sh = rb.shares[d.poolToken]; // if (sh == 0) continue; // UserProtocolRewards storage upr = rb.rewardsByProtocol[d.poolToken]; // for (uint256 i=0; i < d.rewardTokens.length; i++) { // address rToken = d.rewardTokens[i]; // uint256 distrAmount = d.amounts[rToken]; // upr.amounts[rToken] = upr.amounts[rToken].add(distrAmount.mul(sh).div(d.totalShares)); // } // } // rb.nextDistribution = next; // } } // File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol pragma solidity ^0.5.0; contract CapperRole is Initializable, Context { using Roles for Roles.Role; event CapperAdded(address indexed account); event CapperRemoved(address indexed account); Roles.Role private _cappers; function initialize(address sender) public initializer { if (!isCapper(sender)) { _addCapper(sender); } } modifier onlyCapper() { require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role"); _; } function isCapper(address account) public view returns (bool) { return _cappers.has(account); } function addCapper(address account) public onlyCapper { _addCapper(account); } function renounceCapper() public { _removeCapper(_msgSender()); } function _addCapper(address account) internal { _cappers.add(account); emit CapperAdded(account); } function _removeCapper(address account) internal { _cappers.remove(account); emit CapperRemoved(account); } uint256[50] private ______gap; } // File: contracts\modules\savings\SavingsCap.sol pragma solidity ^0.5.12; contract SavingsCap is CapperRole { event UserCapEnabledChange(bool enabled); event UserCapChanged(address indexed protocol, address indexed user, uint256 newCap); event DefaultUserCapChanged(address indexed protocol, uint256 newCap); event ProtocolCapEnabledChange(bool enabled); event ProtocolCapChanged(address indexed protocol, uint256 newCap); event VipUserEnabledChange(bool enabled); event VipUserChanged(address indexed protocol, address indexed user, bool isVip); using SafeERC20 for IERC20; using SafeMath for uint256; struct ProtocolCapInfo { mapping(address => uint256) userCap; //Limit of pool tokens which can be minted for a user during deposit mapping(address=>bool) isVipUser; } mapping(address => ProtocolCapInfo) protocolsCapInfo; //Mapping of protocol to data we need to calculate APY and do distributions bool public userCapEnabled; bool public protocolCapEnabled; mapping(address=>uint256) public defaultUserCap; mapping(address=>uint256) public protocolCap; bool public vipUserEnabled; // Enable VIP user (overrides protocol cap) function initialize(address _capper) public initializer { CapperRole.initialize(_capper); } function setUserCapEnabled(bool _userCapEnabled) public onlyCapper { userCapEnabled = _userCapEnabled; emit UserCapEnabledChange(userCapEnabled); } // function setUserCap(address _protocol, address user, uint256 cap) public onlyCapper { // protocols[_protocol].userCap[user] = cap; // emit UserCapChanged(_protocol, user, cap); // } // function setUserCap(address _protocol, address[] calldata users, uint256[] calldata caps) external onlyCapper { // require(users.length == caps.length, "SavingsModule: arrays length not match"); // for(uint256 i=0; i < users.length; i++) { // protocols[_protocol].userCap[users[i]] = caps[i]; // emit UserCapChanged(_protocol, users[i], caps[i]); // } // } function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper { vipUserEnabled = _vipUserEnabled; emit VipUserEnabledChange(_vipUserEnabled); } function setVipUser(address _protocol, address user, bool isVip) public onlyCapper { protocolsCapInfo[_protocol].isVipUser[user] = isVip; emit VipUserChanged(_protocol, user, isVip); } function setDefaultUserCap(address _protocol, uint256 cap) public onlyCapper { defaultUserCap[_protocol] = cap; emit DefaultUserCapChanged(_protocol, cap); } function setProtocolCapEnabled(bool _protocolCapEnabled) public onlyCapper { protocolCapEnabled = _protocolCapEnabled; emit ProtocolCapEnabledChange(protocolCapEnabled); } function setProtocolCap(address _protocol, uint256 cap) public onlyCapper { protocolCap[_protocol] = cap; emit ProtocolCapChanged(_protocol, cap); } function getUserCapLeft(address _protocol, uint256 _balance) view public returns(uint256) { uint256 cap; if (_balance < defaultUserCap[_protocol]) { cap = defaultUserCap[_protocol] - _balance; } return cap; } function isVipUser(address _protocol, address user) view public returns(bool){ return protocolsCapInfo[_protocol].isVipUser[user]; } function isProtocolCapExceeded(uint256 _poolSupply, address _protocol, address _user) view public returns(bool) { if (protocolCapEnabled) { if ( !(vipUserEnabled && isVipUser(_protocol, _user)) ) { if (_poolSupply > protocolCap[_protocol]) { return true; } } } return false; } } // File: contracts\modules\savings\VaultOperatorRole.sol pragma solidity ^0.5.12; contract VaultOperatorRole is Initializable, Context { using Roles for Roles.Role; event VaultOperatorAdded(address indexed account); event VaultOperatorRemoved(address indexed account); Roles.Role private _managers; function initialize(address sender) public initializer { if (!isVaultOperator(sender)) { _addVaultOperator(sender); } } modifier onlyVaultOperator() { require(isVaultOperator(_msgSender()), "VaultOperatorRole: caller does not have the VaultOperator role"); _; } function addVaultOperator(address account) public onlyVaultOperator { _addVaultOperator(account); } function renounceVaultOperator() public { _removeVaultOperator(_msgSender()); } function isVaultOperator(address account) public view returns (bool) { return _managers.has(account); } function _addVaultOperator(address account) internal { _managers.add(account); emit VaultOperatorAdded(account); } function _removeVaultOperator(address account) internal { _managers.remove(account); emit VaultOperatorRemoved(account); } } // File: contracts\interfaces\defi\IVaultProtocol.sol pragma solidity ^0.5.12; //solhint-disable func-order contract IVaultProtocol { event DepositToVault(address indexed _user, address indexed _token, uint256 _amount); event WithdrawFromVault(address indexed _user, address indexed _token, uint256 _amount); event WithdrawRequestCreated(address indexed _user, address indexed _token, uint256 _amount); event DepositByOperator(uint256 _amount); event WithdrawByOperator(uint256 _amount); event WithdrawRequestsResolved(uint256 _totalDeposit, uint256 _totalWithdraw); event StrategyRegistered(address indexed _vault, address indexed _strategy, string _id); event Claimed(address indexed _vault, address indexed _user, address _token, uint256 _amount); event DepositsCleared(address indexed _vault); event RequestsCleared(address indexed _vault); function registerStrategy(address _strategy) external; function depositToVault(address _user, address _token, uint256 _amount) external; function depositToVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function withdrawFromVault(address _user, address _token, uint256 _amount) external; function withdrawFromVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function operatorAction(address _strategy) external returns(uint256, uint256); function operatorActionOneCoin(address _strategy, address _token) external returns(uint256, uint256); function clearOnHoldDeposits() external; function clearWithdrawRequests() external; function setRemainder(uint256 _amount, uint256 _index) external; function quickWithdraw(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external; function quickWithdrawStrategy() external view returns(address); function claimRequested(address _user) external; function normalizedBalance() external returns(uint256); function normalizedBalance(address _strategy) external returns(uint256); function normalizedVaultBalance() external view returns(uint256); function supportedTokens() external view returns(address[] memory); function supportedTokensCount() external view returns(uint256); function isStrategyRegistered(address _strategy) external view returns(bool); function registeredStrategies() external view returns(address[] memory); function isTokenRegistered(address _token) external view returns (bool); function tokenRegisteredInd(address _token) external view returns(uint256); function totalClaimableAmount(address _token) external view returns (uint256); function claimableAmount(address _user, address _token) external view returns (uint256); function amountOnHold(address _user, address _token) external view returns (uint256); function amountRequested(address _user, address _token) external view returns (uint256); } // File: contracts\interfaces\token\IOperableToken.sol pragma solidity ^0.5.12; interface IOperableToken { function increaseOnHoldValue(address _user, uint256 _amount) external; function decreaseOnHoldValue(address _user, uint256 _amount) external; function onHoldBalanceOf(address _user) external view returns (uint256); } // File: contracts\modules\token\VaultPoolToken.sol pragma solidity ^0.5.12; contract VaultPoolToken is PoolToken, IOperableToken { uint256 internal toBeMinted; mapping(address => uint256) internal onHoldAmount; uint256 totalOnHold; function _mint(address account, uint256 amount) internal { _createDistributionIfReady(); toBeMinted = amount; _updateUserBalance(account); toBeMinted = 0; ERC20._mint(account, amount); userBalanceChanged(account); } function increaseOnHoldValue(address _user, uint256 _amount) public onlyMinter { onHoldAmount[_user] = onHoldAmount[_user].add(_amount); totalOnHold = totalOnHold.add(_amount); } function decreaseOnHoldValue(address _user, uint256 _amount) public onlyMinter { if (onHoldAmount[_user] >= _amount) { _updateUserBalance(_user); onHoldAmount[_user] = onHoldAmount[_user].sub(_amount); if (distributions.length > 0 && nextDistributions[_user] < distributions.length) { nextDistributions[_user] = distributions.length; } totalOnHold = totalOnHold.sub(_amount); userBalanceChanged(_user); } } function onHoldBalanceOf(address _user) public view returns (uint256) { return onHoldAmount[_user]; } function fullBalanceOf(address account) public view returns(uint256){ if (account == address(this)) return 0; //Token itself only holds tokens for others uint256 unclaimed = calculateClaimAmount(account); return balanceOf(account).add(unclaimed); } function distributionBalanceOf(address account) public view returns(uint256) { if (balanceOf(account).add(toBeMinted) <= onHoldAmount[account]) return 0; return balanceOf(account).add(toBeMinted).sub(onHoldAmount[account]); } function distributionTotalSupply() public view returns(uint256){ return totalSupply().sub(totalOnHold); } function userBalanceChanged(address account) internal { //Disable rewards for the vaults } } // File: contracts\interfaces\savings\IVaultSavings.sol pragma solidity ^0.5.12; //solhint-disable func-order contract IVaultSavings { event VaultRegistered(address protocol, address poolToken); event YieldDistribution(address indexed poolToken, uint256 amount); event DepositToken(address indexed protocol, address indexed token, uint256 dnAmount); event Deposit(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee); event WithdrawToken(address indexed protocol, address indexed token, uint256 dnAmount); event Withdraw(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee); function deposit(address[] calldata _protocols, address[] calldata _tokens, uint256[] calldata _dnAmounts) external returns(uint256[] memory); function deposit(address _protocol, address[] calldata _tokens, uint256[] calldata _dnAmounts) external returns(uint256); function withdraw(address _vaultProtocol, address[] calldata _tokens, uint256[] calldata _amounts, bool isQuick) external returns(uint256); function poolTokenByProtocol(address _protocol) external view returns(address); function supportedVaults() public view returns(address[] memory); function isVaultRegistered(address _protocol) public view returns(bool); function registerVault(IVaultProtocol protocol, VaultPoolToken poolToken) external; //function quickWithdraw(address _vaultProtocol, address[] calldata _tokens, uint256[] calldata _amounts) external returns(uint256); function handleOperatorActions(address _vaultProtocol, address _strategy, address _token) external; function claimAllRequested(address _vaultProtocol) external; } // File: contracts\interfaces\defi\IStrategyCurveFiSwapCrv.sol pragma solidity ^0.5.12; interface IStrategyCurveFiSwapCrv { event CrvClaimed(string indexed id, address strategy, uint256 amount); function curveFiTokenBalance() external view returns(uint256); function performStrategyStep1() external; function performStrategyStep2(bytes calldata _data, address _token) external; } // File: contracts\modules\savings\VaultSavingsModule.sol pragma solidity ^0.5.12; contract VaultSavingsModule is Module, IVaultSavings, AccessChecker, RewardDistributions, SavingsCap, VaultOperatorRole { uint256 constant MAX_UINT256 = uint256(-1); using SafeERC20 for IERC20; using SafeMath for uint256; struct VaultInfo { VaultPoolToken poolToken; uint256 previousBalance; } address[] internal registeredVaults; mapping(address => VaultInfo) vaults; mapping(address => address) poolTokenToVault; // ------ // Settings methods // ------ function initialize(address _pool) public initializer { Module.initialize(_pool); SavingsCap.initialize(_msgSender()); VaultOperatorRole.initialize(_msgSender()); } function registerVault(IVaultProtocol protocol, VaultPoolToken poolToken) public onlyOwner { require(!isVaultRegistered(address(protocol)), "Vault is already registered"); registeredVaults.push(address(protocol)); vaults[address(protocol)] = VaultInfo({ poolToken: poolToken, previousBalance: protocol.normalizedBalance() }); poolTokenToVault[address(poolToken)] = address(protocol); uint256 normalizedBalance = vaults[address(protocol)].previousBalance; if(normalizedBalance > 0) { uint256 ts = poolToken.totalSupply(); if(ts < normalizedBalance) { poolToken.mint(_msgSender(), normalizedBalance.sub(ts)); } } emit VaultRegistered(address(protocol), address(poolToken)); } // ------ // User interface // ------ //Deposits several tokens into single Vault function deposit(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) public operationAllowed(IAccessModule.Operation.Deposit) returns(uint256) { require(isVaultRegistered(_protocol), "Vault is not registered"); depositToProtocol(_protocol, _tokens, _dnAmounts); uint256 nAmount; for (uint256 i=0; i < _tokens.length; i++) { nAmount = nAmount.add(CalcUtils.normalizeAmount(_tokens[i], _dnAmounts[i])); } VaultPoolToken poolToken = VaultPoolToken(vaults[_protocol].poolToken); poolToken.mint(_msgSender(), nAmount); require(!isProtocolCapExceeded(poolToken.totalSupply(), _protocol, _msgSender()), "Deposit exeeds protocols cap"); uint256 cap; if (userCapEnabled) { cap = userCap(_protocol, _msgSender()); require(cap >= nAmount, "Deposit exeeds user cap"); } emit Deposit(_protocol, _msgSender(), nAmount, 0); return nAmount; } //Deposits into several vaults but one coin at time function deposit(address[] memory _protocols, address[] memory _tokens, uint256[] memory _dnAmounts) public operationAllowed(IAccessModule.Operation.Deposit) returns(uint256[] memory) { require(_protocols.length == _tokens.length && _tokens.length == _dnAmounts.length, "Size of arrays does not match"); uint256[] memory ptAmounts = new uint256[](_protocols.length); address[] memory tkns = new address[](1); uint256[] memory amnts = new uint256[](1); for (uint256 i=0; i < _protocols.length; i++) { tkns[0] = _tokens[i]; amnts[0] = _dnAmounts[i]; ptAmounts[i] = deposit(_protocols[i], tkns, amnts); } return ptAmounts; } function depositToProtocol(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) internal { for (uint256 i=0; i < _tokens.length; i++) { address tkn = _tokens[i]; IERC20(tkn).safeTransferFrom(_msgSender(), _protocol, _dnAmounts[i]); IVaultProtocol(_protocol).depositToVault(_msgSender(), tkn, _dnAmounts[i]); emit DepositToken(_protocol, tkn, _dnAmounts[i]); } } //Withdraw several tokens from a Vault in regular way or in quickWay function withdraw(address _vaultProtocol, address[] memory _tokens, uint256[] memory _amounts, bool isQuick) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256) { require(isVaultRegistered(_vaultProtocol), "Vault is not registered"); require(_tokens.length == _amounts.length, "Size of arrays does not match"); VaultPoolToken poolToken = VaultPoolToken(vaults[_vaultProtocol].poolToken); uint256 actualAmount; uint256 normAmount; for (uint256 i = 0; i < _amounts.length; i++) { normAmount = CalcUtils.normalizeAmount(_tokens[i], _amounts[i]); actualAmount = actualAmount.add(normAmount); emit WithdrawToken(address(_vaultProtocol), _tokens[i], normAmount); } if (isQuick) { uint256 yield = quickWithdraw(_vaultProtocol, _tokens, _amounts, normAmount); if (yield > 0) { createYieldDistribution(poolToken, yield); } } else { if (_tokens.length == 1) { IVaultProtocol(_vaultProtocol).withdrawFromVault(_msgSender(), _tokens[0], _amounts[0]); } else { IVaultProtocol(_vaultProtocol).withdrawFromVault(_msgSender(), _tokens, _amounts); } } poolToken.burnFrom(_msgSender(), actualAmount); emit Withdraw(_vaultProtocol, _msgSender(), actualAmount, 0); return actualAmount; } function quickWithdraw(address _vaultProtocol, address[] memory _tokens, uint256[] memory _amounts, uint256 normAmount) internal returns(uint256) { uint256 nBalanceBefore = distributeYieldInternal(_vaultProtocol); IVaultProtocol(_vaultProtocol).quickWithdraw(_msgSender(), _tokens, _amounts); uint256 nBalanceAfter = updateProtocolBalance(_vaultProtocol); uint256 yield; uint256 calcBalanceAfter = nBalanceBefore.sub(normAmount); if (nBalanceAfter > calcBalanceAfter) { yield = nBalanceAfter.sub(calcBalanceAfter); } return yield; } //Withdraw several tokens from several Vaults function withdrawAll(address[] memory _vaults, address[] memory _tokens, uint256[] memory _dnAmounts) public operationAllowed(IAccessModule.Operation.Withdraw) returns(uint256[] memory) { require(_tokens.length == _dnAmounts.length, "Size of arrays does not match"); uint256[] memory ptAmounts = new uint256[](_vaults.length); uint256 curInd; uint256 lim; uint256 nTokens; for (uint256 i=0; i < _vaults.length; i++) { nTokens = IVaultProtocol(_vaults[i]).supportedTokensCount(); lim = curInd + nTokens; require(_tokens.length >= lim, "Incorrect tokens length"); address[] memory tkns = new address[](nTokens); uint256[] memory amnts = new uint256[](nTokens); for (uint256 j = curInd; j < lim; j++) { tkns[j-curInd] = _tokens[j]; amnts[j-curInd] = _dnAmounts[j]; } ptAmounts[i] = withdraw(_vaults[i], tkns, amnts, false); curInd += nTokens; } return ptAmounts; } function claimAllRequested(address _vaultProtocol) public { require(isVaultRegistered(_vaultProtocol), "Vault is not registered"); IVaultProtocol(_vaultProtocol).claimRequested(_msgSender()); } // ------ // Operator interface // ------ function handleOperatorActions(address _vaultProtocol, address _strategy, address _token) public onlyVaultOperator { uint256 totalDeposit; uint256 totalWithdraw; VaultPoolToken poolToken = VaultPoolToken(vaults[_vaultProtocol].poolToken); uint256 nBalanceBefore = distributeYieldInternal(_vaultProtocol); if (_token == address(0)) { (totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorAction(_strategy); } else { (totalDeposit, totalWithdraw) = IVaultProtocol(_vaultProtocol).operatorActionOneCoin(_strategy, _token); } //Protocol records can be cleared now uint256 nBalanceAfter = updateProtocolBalance(_vaultProtocol); uint256 yield; uint256 calcBalanceAfter = nBalanceBefore.add(totalDeposit).sub(totalWithdraw); if (nBalanceAfter > calcBalanceAfter) { yield = nBalanceAfter.sub(calcBalanceAfter); } if (yield > 0) { createYieldDistribution(poolToken, yield); } } function clearProtocolStorage(address _vaultProtocol) public onlyVaultOperator { IVaultProtocol(_vaultProtocol).clearOnHoldDeposits(); IVaultProtocol(_vaultProtocol).clearWithdrawRequests(); } function distributeYield(address _vaultProtocol) public { distributeYieldInternal(_vaultProtocol); } function setVaultRemainder(address _vaultProtocol, uint256 _amount, uint256 _index) public onlyVaultOperator { IVaultProtocol(_vaultProtocol).setRemainder(_amount, _index); } function callStrategyStep(address _vaultProtocol, address _strategy, bool _distrYield, bytes memory _strategyData) public onlyVaultOperator { require(IVaultProtocol(_vaultProtocol).isStrategyRegistered(_strategy), "Strategy is not registered"); uint256 oldVaultBalance = IVaultProtocol(_vaultProtocol).normalizedVaultBalance(); (bool success, bytes memory result) = _strategy.call(_strategyData); if(!success) assembly { revert(add(result,32), result) //Reverts with same revert reason } if (_distrYield) { uint256 newVaultBalance; newVaultBalance = IVaultProtocol(_vaultProtocol).normalizedVaultBalance(); if (newVaultBalance > oldVaultBalance) { uint256 yield = newVaultBalance.sub(oldVaultBalance); vaults[_vaultProtocol].previousBalance = vaults[_vaultProtocol].previousBalance.add(yield); createYieldDistribution(vaults[_vaultProtocol].poolToken, yield); } } } // ------ // Getters and checkers // ------ function poolTokenByProtocol(address _vaultProtocol) public view returns(address) { return address(vaults[_vaultProtocol].poolToken); } function protocolByPoolToken(address _poolToken) public view returns(address) { return poolTokenToVault[_poolToken]; } function userCap(address _protocol, address user) public view returns(uint256) { uint256 balance = vaults[_protocol].poolToken.balanceOf(user); return getUserCapLeft(_protocol, balance); } function isVaultRegistered(address _protocol) public view returns(bool) { for (uint256 i = 0; i < registeredVaults.length; i++){ if (registeredVaults[i] == _protocol) return true; } return false; } function supportedVaults() public view returns(address[] memory) { return registeredVaults; } // ------ // Yield distribution internal helpers // ------ function distributeYieldInternal(address _vaultProtocol) internal returns(uint256){ uint256 currentBalance = IVaultProtocol(_vaultProtocol).normalizedBalance(); VaultInfo storage pi = vaults[_vaultProtocol]; VaultPoolToken poolToken = VaultPoolToken(pi.poolToken); if(currentBalance > pi.previousBalance) { uint256 yield = currentBalance.sub(pi.previousBalance); pi.previousBalance = currentBalance; createYieldDistribution(poolToken, yield); } return currentBalance; } function createYieldDistribution(VaultPoolToken poolToken, uint256 yield) internal { poolToken.distribute(yield); emit YieldDistribution(address(poolToken), yield); } function updateProtocolBalance(address _protocol) internal returns(uint256){ uint256 currentBalance = IVaultProtocol(_protocol).normalizedBalance(); vaults[_protocol].previousBalance = currentBalance; return currentBalance; } }
------ Settings methods ------
function initialize(address _pool) public initializer { Module.initialize(_pool); SavingsCap.initialize(_msgSender()); VaultOperatorRole.initialize(_msgSender()); }
1,117,601
./full_match/97/0x65d02A3481F3c25DE96671E30044fad2D060ae95/sources/project:/contracts/Exchange/exchange.sol
Include address in blacklist by UPDATER_ROLE. account. Emits {Blacklisted} event./
function includeInBlacklist(address account) external onlyRole(UPDATER_ROLE) { require(account != address(0), "Exchange: Cant be zero address"); require(!blacklisted[account], "Exchange: Account is already blacklisted"); blacklisted[account] = true; emit Blacklisted(account); }
3,276,170
./full_match/11155111/0xFB34DaDd5f3Aba55004C448AcFd24fAF5A4Ff83E/sources/contracts/history/History.sol
Get a specific claim regarding a specific DApp. There are several requirements for this function to be called successfully. `_proofContext` MUST be well-encoded. In Solidity, it can be constructed as `abi.encode(claimIndex)`, where `claimIndex` is the claim index (type `uint256`). `claimIndex` MUST be inside the interval `[0, n)` where `n` is the number of claims that have been submitted to `_dapp` already. @inheritdoc IHistory
function getClaim( address _dapp, bytes calldata _proofContext ) external view override returns (bytes32, uint256, uint256) { uint256 claimIndex = abi.decode(_proofContext, (uint256)); Claim memory claim = claims[_dapp][claimIndex]; return (claim.epochHash, claim.firstIndex, claim.lastIndex); }
3,828,127
// SPDX-License-Identifier: Unlicense /* Glyph Pets inspires by WAGMIpet NFT by m1guelpf.eth, which was inspired by dhof.eth's wagmipet contract (mainnet:0xecb504d39723b0be0e3a9aa33d646642d1051ee1) */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract GlyphPets is Ownable, ERC721Enumerable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; event CaretakerLoved( address indexed caretaker, uint256 indexed tokenId, uint256 amount ); struct Pet { uint256 lastFeedBlock; uint256 lastCleanBlock; uint256 lastPlayBlock; uint256 lastSleepBlock; uint8 hunger; uint8 uncleanliness; uint8 boredom; uint8 sleepiness; } mapping(uint256 => Pet) internal pets; mapping(address => uint256) public love; ERC721 lilglyphs; constructor(address lilGlyphAddress) ERC721("Glyph Pets", "GP") { lilglyphs = ERC721(lilGlyphAddress); } function glyphInPlay(uint256 tokenId) public view returns (bool) { require(_exists(tokenId), "token id invalid"); return getAlive(tokenId); } function adopt(uint256 tokenId) public returns (uint256) { bool exists = _exists(tokenId); if (exists) { require(!getAlive(tokenId) && ownerOf(tokenId) == msg.sender, "in play"); } else { require(lilglyphs.ownerOf(tokenId) == _msgSender(), "not owned"); } pets[tokenId] = Pet( block.number, block.number, block.number, block.number, 0, 0, 0, 0 ); if (!exists) { _mint(_msgSender(), tokenId); } return tokenId; } function addLove( address caretaker, uint256 tokenId, uint256 amount ) internal { love[caretaker] += amount; emit CaretakerLoved(caretaker, tokenId, amount); } function feed(uint256 tokenId) public { require(_exists(tokenId), "pet does not exist"); require(ownerOf(tokenId) == _msgSender(), "not your pet"); require(getHunger(tokenId) > 0, "i dont need to eat"); require(getAlive(tokenId), "no longer with us"); require(getBoredom(tokenId) < 80, "im too tired to eat"); require(getUncleanliness(tokenId) < 80, "im feeling too gross to eat"); require(getHunger(tokenId) > 0, "i dont need to eat"); pets[tokenId].lastFeedBlock = block.number; pets[tokenId].hunger = 0; pets[tokenId].boredom += 10; pets[tokenId].uncleanliness += 3; addLove(_msgSender(), tokenId, 1); } function clean(uint256 tokenId) public { require(_exists(tokenId), "pet does not exist"); require(ownerOf(tokenId) == _msgSender(), "not your pet"); require(getAlive(tokenId), "no longer with us"); require(getUncleanliness(tokenId) > 0, "i dont need a bath"); pets[tokenId].lastCleanBlock = block.number; pets[tokenId].uncleanliness = 0; addLove(_msgSender(), tokenId, 1); } function play(uint256 tokenId) public { require(_exists(tokenId), "pet does not exist"); require(ownerOf(tokenId) == _msgSender(), "not your pet"); require(getAlive(tokenId), "no longer with us"); require(getHunger(tokenId) < 80, "im too hungry to play"); require(getSleepiness(tokenId) < 80, "im too sleepy to play"); require(getUncleanliness(tokenId) < 80, "im feeling too gross to play"); require(getBoredom(tokenId) > 0, "i dont wanna play"); pets[tokenId].lastPlayBlock = block.number; pets[tokenId].boredom = 0; pets[tokenId].hunger += 10; pets[tokenId].sleepiness += 10; pets[tokenId].uncleanliness += 5; addLove(_msgSender(), tokenId, 1); } function sleep(uint256 tokenId) public { require(_exists(tokenId), "pet does not exist"); require(ownerOf(tokenId) == _msgSender(), "not your pet"); require(getAlive(tokenId), "no longer with us"); require(getUncleanliness(tokenId) < 80, "im feeling too gross to sleep"); require(getSleepiness(tokenId) > 0, "im not feeling sleepy"); pets[tokenId].lastSleepBlock = block.number; pets[tokenId].sleepiness = 0; pets[tokenId].uncleanliness += 5; addLove(_msgSender(), tokenId, 1); } function getStatus(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "pet does not exist"); uint256 mostNeeded = 0; string[5] memory goodStatus = [ "gm", "im feeling great", "we gmi", "all good", "i love u" ]; string memory status = goodStatus[block.number % 5]; uint256 hunger = getHunger(tokenId); uint256 uncleanliness = getUncleanliness(tokenId); uint256 boredom = getBoredom(tokenId); uint256 sleepiness = getSleepiness(tokenId); if (getAlive(tokenId) == false) { return "no longer with us"; } if (hunger > 50 && hunger > mostNeeded) { mostNeeded = hunger; status = "im hungry"; } if (uncleanliness > 50 && uncleanliness > mostNeeded) { mostNeeded = uncleanliness; status = "i need a bath"; } if (boredom > 50 && boredom > mostNeeded) { mostNeeded = boredom; status = "im bored"; } if (sleepiness > 50 && sleepiness > mostNeeded) { mostNeeded = sleepiness; status = "im sleepy"; } return status; } function getAlive(uint256 tokenId) public view returns (bool) { require(_exists(tokenId), "pet does not exist"); return getHunger(tokenId) < 101 && getUncleanliness(tokenId) < 101 && getBoredom(tokenId) < 101 && getSleepiness(tokenId) < 101; } function getHunger(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "pet does not exist"); return pets[tokenId].hunger + ((block.number - pets[tokenId].lastFeedBlock) / 400); } function getUncleanliness(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "pet does not exist"); return pets[tokenId].uncleanliness + ((block.number - pets[tokenId].lastCleanBlock) / 400); } function getBoredom(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "pet does not exist"); return pets[tokenId].boredom + ((block.number - pets[tokenId].lastPlayBlock) / 400); } function getSleepiness(uint256 tokenId) public view returns (uint256) { require(_exists(tokenId), "pet does not exist"); return pets[tokenId].sleepiness + ((block.number - pets[tokenId].lastSleepBlock) / 400); } function getStats(uint256 tokenId) public view returns (uint256[5] memory) { return [ getAlive(tokenId) ? 1 : 0, getHunger(tokenId), getUncleanliness(tokenId), getBoredom(tokenId), getSleepiness(tokenId) ]; } function countNeighbors( uint256 id, uint256 idx, uint256 index ) internal pure returns (uint256) { uint256 top = idx >= 5 ? getBoolean(id, idx - 5) : 0; uint256 bottom = idx <= 44 ? getBoolean(id, idx + 5) : 0; uint256 left = idx > 0 && index != 0 ? getBoolean(id, idx - 1) : 0; uint256 right = idx < 49 && index != 4 ? getBoolean(id, idx + 1) : 0; return top + bottom + left + right; } function setBoolean( uint256 _packedBools, uint256 _boolNumber, uint256 _value ) public pure returns (uint256) { if (_value == 1) return _packedBools | (uint256(1) << _boolNumber); else return _packedBools & ~(uint256(1) << _boolNumber); } function getBoolean(uint256 _packedBools, uint256 _boolNumber) public pure returns (uint256) { uint256 flag = (_packedBools >> _boolNumber) & uint256(1); return flag; } string[] baseColors = [ "#FFD12A", "#4F86F7", "#FFD3F8", "#DA2647", "#FFFF31", "#44D7A8", "#A6E7FF", "#6F2DA8", "#DA614E", "#253529", "#1A1110", "#B2F302", "#214FC6", "#FF5050", "#0048BA", "#B0BF1A", "#7CB9E8", "#C0E8D5", "#B284BE", "#FF7E00", "#9966CC", "#66FF00" ]; string[] buttonColors = [ "#FF3855", "#FFAA1D", "#FFF700", "#299617", "#FF5470", "#BFAFB2", "#E936A7", "#66FF66", "#FF00CC", "#848482", "#318CE7", "#66FF00", "#FB607F" ]; function compareStr(string memory a, string memory b) internal pure returns (bool) { if (bytes(a).length != bytes(b).length) { return false; } else { return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } } function getSvg(uint256 tokenId) public view returns (string memory) { uint256 ppd = 5; string memory svg; for (uint256 i = 0; i < 50; i++) { uint256 x = (i - ((i / 5) * 5)); if (getBoolean(tokenId, i) == 1) { continue; } else if (countNeighbors(tokenId, i, x) > 0) { string memory color1 = "3B2F2F"; string memory color2 = "3B2F2F"; string memory status = getStatus(tokenId); if (!getAlive(tokenId)) { color1 = "DEAD"; color2 = color1; } else if (compareStr(status, "im hungry")) { color1 = "E52B50"; color2 = "FFBF00"; } else if (compareStr(status, "i need a bath")) { color1 = "9F8170"; color2 = color1; } else if (compareStr(status, "im bored")) { color1 = "FB607F"; color2 = color1; } else if (compareStr(status, "im sleepy")) { color1 = "8A2BE2"; color2 = color1; } string memory rect = string( abi.encodePacked( '<rect x="', Strings.toString(x * ppd), '" y="', Strings.toString((i / 5) * ppd), '" width="5" height="5" style="fill:#', color1, '"></rect>' ) ); string memory rectFlip = string( abi.encodePacked( '<rect data-id="', Strings.toString(i), '" x="', Strings.toString((10 - x - 1) * ppd), '" y="', Strings.toString((i / 5) * ppd), '" width="5" height="5" style="fill:#', color2, '"></rect>' ) ); svg = string(abi.encodePacked(svg, rect, rectFlip)); } else { continue; } } string[5] memory wrap; wrap[0] = string( abi.encodePacked( '<svg fill="#FFF" height="270" viewBox="0 0 210 270" width="210" xmlns="http://www.w3.org/2000/svg"> <defs><linearGradient id="g" gradientTransform="rotate(', Strings.toString(tokenId % 180), ')"><stop offset="5%" stop-color="', baseColors[(tokenId / 2) % baseColors.length], '" /><stop offset="95%" stop-color="', baseColors[(tokenId) % baseColors.length], '" /></linearGradient></defs><g><rect width="210" height="270"></rect><path fill="url(#g)" d="m105 0c10.2 0 18.9 8.4 18.6 18.6 0 2.1-.3 4.2-.9 6 49.5 12 87.3 72.9 87.3 146.4 0 54.6-47.1 99-105 99s-105-44.4-105-99c0-73.5 37.8-134.4 87-146.1-.6-1.8-.9-3.9-.9-6 0-10.5 8.7-18.9 18.9-18.9zm45 97.5h-90c-4.2 0-7.5 3.3-7.5 7.5v90c0 4.2 3.3 7.5 7.5 7.5h90c4.2 0 7.5-3.3 7.5-7.5v-90c0-4.2-3.3-7.5-7.5-7.5zm-45-86.1c-4.2 0-7.5 3.3-7.5 7.5s3.3 7.5 7.5 7.5 7.5-3.3 7.5-7.5-3.3-7.5-7.5-7.5z"/><g transform="translate(80 125)">' ) ); if (getAlive(tokenId)) { wrap[1] = string( abi.encodePacked( '<animateTransform xmlns="http://www.w3.org/2000/svg" attributeName="transform" attributeType="XML" type="translate" dur=".9s" repeatCount="indefinite" autoReverse="true" values="80 125; 80 122; 80 125;"/>', svg, "</g>" ) ); } else { wrap[1] = string(abi.encodePacked(svg, "</g>")); } wrap[2] = string( abi.encodePacked( '<g fill="', buttonColors[tokenId % buttonColors.length], '">' ) ); wrap[ 3 ] = '<path d="m75 247.5c-4.2 0-7.5-3.3-7.5-7.5s3.3-7.5 7.5-7.5 7.5 3.3 7.5 7.5-3.3 7.5-7.5 7.5z"/><path d="m105 255c-4.2 0-7.5-3.3-7.5-7.5s3.3-7.5 7.5-7.5 7.5 3.3 7.5 7.5-3.3 7.5-7.5 7.5z"/><path d="m135 247.5c-4.2 0-7.5-3.3-7.5-7.5s3.3-7.5 7.5-7.5 7.5 3.3 7.5 7.5-3.3 7.5-7.5 7.5z"/>'; wrap[4] = "</g></g></svg>"; return string(abi.encodePacked(wrap[0], wrap[1], wrap[2], wrap[3], wrap[4])); } function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "pet does not exist"); // solhint-disable-next-line quotes string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Glyph Pet #', Strings.toString(tokenId), '", "background_color": "FFFFFF", "description": "Glyph Pets are virtual pets living on the blockchain.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(getSvg(tokenId))), '"}' ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", json)); } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add( out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF) ) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
solhint-disable-next-line quotes
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) { require(_exists(tokenId), "pet does not exist"); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "Glyph Pet #', Strings.toString(tokenId), '", "background_color": "FFFFFF", "description": "Glyph Pets are virtual pets living on the blockchain.", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(getSvg(tokenId))), '"}' ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", json)); }
5,451,727
pragma solidity ^0.4.23; // File: contracts/NokuPricingPlan.sol /** * @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan. */ contract NokuPricingPlan { /** * @dev Pay the fee for the service identified by the specified name. * The fee amount shall already be approved by the client. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @param client The client of the target service. * @return true if fee has been paid. */ function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid); /** * @dev Get the usage fee for the service identified by the specified name. * The returned fee amount shall be approved before using #payFee method. * @param serviceName The name of the target service. * @param multiplier The multiplier of the base service fee to apply. * @return The amount to approve before really paying such fee. */ function usageFee(bytes32 serviceName, uint256 multiplier) public constant returns(uint fee); } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/NokuCustomToken.sol contract NokuCustomToken is Ownable { event LogBurnFinished(); event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); // The pricing plan determining the fee to be paid in NOKU tokens by customers for using Noku services NokuPricingPlan public pricingPlan; // The entity acting as Custom Token service provider i.e. Noku address public serviceProvider; // Flag indicating if Custom Token burning has been permanently finished or not. bool public burningFinished; /** * @dev Modifier to make a function callable only by service provider i.e. Noku. */ modifier onlyServiceProvider() { require(msg.sender == serviceProvider, "caller is not service provider"); _; } modifier canBurn() { require(!burningFinished, "burning finished"); _; } constructor(address _pricingPlan, address _serviceProvider) internal { require(_pricingPlan != 0, "_pricingPlan is zero"); require(_serviceProvider != 0, "_serviceProvider is zero"); pricingPlan = NokuPricingPlan(_pricingPlan); serviceProvider = _serviceProvider; } /** * @dev Presence of this function indicates the contract is a Custom Token. */ function isCustomToken() public pure returns(bool isCustom) { return true; } /** * @dev Stop burning new tokens. * @return true if the operation was successful. */ function finishBurning() public onlyOwner canBurn returns(bool finished) { burningFinished = true; emit LogBurnFinished(); return true; } /** * @dev Change the pricing plan of service fee to be paid in NOKU tokens. * @param _pricingPlan The pricing plan of NOKU token to be paid, zero means flat subscription. */ function setPricingPlan(address _pricingPlan) public onlyServiceProvider { require(_pricingPlan != 0, "_pricingPlan is 0"); require(_pricingPlan != address(pricingPlan), "_pricingPlan == pricingPlan"); pricingPlan = NokuPricingPlan(_pricingPlan); emit LogPricingPlanChanged(msg.sender, _pricingPlan); } } // File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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(); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/NokuTokenBurner.sol contract BurnableERC20 is ERC20 { function burn(uint256 amount) public returns (bool burned); } /** * @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received * ERC20-compliant tokens and distribute the remainder to the configured wallet. */ contract NokuTokenBurner is Pausable { using SafeMath for uint256; event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet); event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage); // The wallet receiving the unburnt tokens. address public wallet; // The percentage of tokens to burn after being received (range [0, 100]) uint256 public burningPercentage; // The cumulative amount of burnt tokens. uint256 public burnedTokens; // The cumulative amount of tokens transferred back to the wallet. uint256 public transferredTokens; /** * @dev Create a new NokuTokenBurner with predefined burning fraction. * @param _wallet The wallet receiving the unburnt tokens. */ constructor(address _wallet) public { require(_wallet != address(0), "_wallet is zero"); wallet = _wallet; burningPercentage = 100; emit LogNokuTokenBurnerCreated(msg.sender, _wallet); } /** * @dev Change the percentage of tokens to burn after being received. * @param _burningPercentage The percentage of tokens to be burnt. */ function setBurningPercentage(uint256 _burningPercentage) public onlyOwner { require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]"); require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one"); burningPercentage = _burningPercentage; emit LogBurningPercentageChanged(msg.sender, _burningPercentage); } /** * @dev Called after burnable tokens has been transferred for burning. * @param _token THe extended ERC20 interface supported by the sent tokens. * @param _amount The amount of burnable tokens just arrived ready for burning. */ function tokenReceived(address _token, uint256 _amount) public whenNotPaused { require(_token != address(0), "_token is zero"); require(_amount > 0, "_amount is zero"); uint256 amountToBurn = _amount.mul(burningPercentage).div(100); if (amountToBurn > 0) { assert(BurnableERC20(_token).burn(amountToBurn)); burnedTokens = burnedTokens.add(amountToBurn); } uint256 amountToTransfer = _amount.sub(amountToBurn); if (amountToTransfer > 0) { assert(BurnableERC20(_token).transfer(wallet, amountToTransfer)); transferredTokens = transferredTokens.add(amountToTransfer); } } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _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's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/TokenTimelock.sol /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint256 public releaseTime; function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public { // solium-disable-next-line security/no-block-members require(_releaseTime > block.timestamp); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } // File: openzeppelin-solidity/contracts/token/ERC20/TokenVesting.sol /* solium-disable security/no-block-members */ pragma solidity ^0.4.21; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ function TokenVesting( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } // File: contracts/NokuCustomERC20.sol /** * @dev The NokuCustomERC20Token contract is a custom ERC20-compliant token available in the Noku Service Platform (NSP). * The Noku customer is able to choose the token name, symbol, decimals, initial supply and to administer its lifecycle * by minting or burning tokens in order to increase or decrease the token supply. */ contract NokuCustomERC20 is NokuCustomToken, DetailedERC20, MintableToken, BurnableToken { using SafeMath for uint256; event LogNokuCustomERC20Created( address indexed caller, string indexed name, string indexed symbol, uint8 decimals, uint256 transferableFromBlock, uint256 lockEndBlock, address pricingPlan, address serviceProvider ); event LogMintingFeeEnabledChanged(address indexed caller, bool indexed mintingFeeEnabled); event LogInformationChanged(address indexed caller, string name, string symbol); event LogTransferFeePaymentFinished(address indexed caller); event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage); // Flag indicating if minting fees are enabled or disabled bool public mintingFeeEnabled; // Block number from which tokens are initially transferable uint256 public transferableFromBlock; // Block number from which initial lock ends uint256 public lockEndBlock; // The initially locked balances by address mapping (address => uint256) public initiallyLockedBalanceOf; // The fee percentage for Custom Token transfer or zero if transfer is free of charge uint256 public transferFeePercentage; // Flag indicating if fee payment in Custom Token transfer has been permanently finished or not. bool public transferFeePaymentFinished; bytes32 public constant BURN_SERVICE_NAME = "NokuCustomERC20.burn"; bytes32 public constant MINT_SERVICE_NAME = "NokuCustomERC20.mint"; modifier canTransfer(address _from, uint _value) { require(block.number >= transferableFromBlock, "token not transferable"); if (block.number < lockEndBlock) { uint256 locked = lockedBalanceOf(_from); if (locked > 0) { uint256 newBalance = balanceOf(_from).sub(_value); require(newBalance >= locked, "_value exceeds locked amount"); } } _; } constructor( string _name, string _symbol, uint8 _decimals, uint256 _transferableFromBlock, uint256 _lockEndBlock, address _pricingPlan, address _serviceProvider ) NokuCustomToken(_pricingPlan, _serviceProvider) DetailedERC20(_name, _symbol, _decimals) public { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); require(_lockEndBlock >= _transferableFromBlock, "_lockEndBlock lower than _transferableFromBlock"); transferableFromBlock = _transferableFromBlock; lockEndBlock = _lockEndBlock; mintingFeeEnabled = true; emit LogNokuCustomERC20Created( msg.sender, _name, _symbol, _decimals, _transferableFromBlock, _lockEndBlock, _pricingPlan, _serviceProvider ); } function setMintingFeeEnabled(bool _mintingFeeEnabled) public onlyOwner returns(bool successful) { require(_mintingFeeEnabled != mintingFeeEnabled, "_mintingFeeEnabled == mintingFeeEnabled"); mintingFeeEnabled = _mintingFeeEnabled; emit LogMintingFeeEnabledChanged(msg.sender, _mintingFeeEnabled); return true; } /** * @dev Change the Custom Token detailed information after creation. * @param _name The name to assign to the Custom Token. * @param _symbol The symbol to assign to the Custom Token. */ function setInformation(string _name, string _symbol) public onlyOwner returns(bool successful) { require(bytes(_name).length > 0, "_name is empty"); require(bytes(_symbol).length > 0, "_symbol is empty"); name = _name; symbol = _symbol; emit LogInformationChanged(msg.sender, _name, _symbol); return true; } /** * @dev Stop trasfer fee payment for tokens. * @return true if the operation was successful. */ function finishTransferFeePayment() public onlyOwner returns(bool finished) { require(!transferFeePaymentFinished, "transfer fee finished"); transferFeePaymentFinished = true; emit LogTransferFeePaymentFinished(msg.sender); return true; } /** * @dev Change the transfer fee percentage to be paid in Custom tokens. * @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100]. */ function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner { require(0 <= _transferFeePercentage && _transferFeePercentage <= 100, "_transferFeePercentage not in [0, 100]"); require(_transferFeePercentage != transferFeePercentage, "_transferFeePercentage equal to current value"); transferFeePercentage = _transferFeePercentage; emit LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage); } function lockedBalanceOf(address _to) public constant returns(uint256 locked) { uint256 initiallyLocked = initiallyLockedBalanceOf[_to]; if (block.number >= lockEndBlock) return 0; else if (block.number <= transferableFromBlock) return initiallyLocked; uint256 releaseForBlock = initiallyLocked.div(lockEndBlock.sub(transferableFromBlock)); uint256 released = block.number.sub(transferableFromBlock).mul(releaseForBlock); return initiallyLocked.sub(released); } /** * @dev Get the fee to be paid for the transfer of NOKU tokens. * @param _value The amount of NOKU tokens to be transferred. */ function transferFee(uint256 _value) public view returns(uint256 usageFee) { return _value.mul(transferFeePercentage).div(100); } /** * @dev Check if token transfer is free of any charge or not. * @return true if transfer is free of any charge. */ function freeTransfer() public view returns (bool isTransferFree) { return transferFeePaymentFinished || transferFeePercentage == 0; } /** * @dev Override #transfer for optionally paying fee to Custom token owner. */ function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transfer(_to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transfer(owner, usageFee); bool netValueTransferred = super.transfer(_to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Override #transferFrom for optionally paying fee to Custom token owner. */ function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns(bool transferred) { if (freeTransfer()) { return super.transferFrom(_from, _to, _value); } else { uint256 usageFee = transferFee(_value); uint256 netValue = _value.sub(usageFee); bool feeTransferred = super.transferFrom(_from, owner, usageFee); bool netValueTransferred = super.transferFrom(_from, _to, netValue); return feeTransferred && netValueTransferred; } } /** * @dev Burn a specific amount of tokens, paying the service fee. * @param _amount The amount of token to be burned. */ function burn(uint256 _amount) public canBurn { require(_amount > 0, "_amount is zero"); super.burn(_amount); require(pricingPlan.payFee(BURN_SERVICE_NAME, _amount, msg.sender), "burn fee failed"); } /** * @dev Mint a specific amount of tokens, paying the service fee. * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { require(_to != 0, "_to is zero"); require(_amount > 0, "_amount is zero"); super.mint(_to, _amount); if (mintingFeeEnabled) { require(pricingPlan.payFee(MINT_SERVICE_NAME, _amount, msg.sender), "mint fee failed"); } return true; } /** * @dev Mint new locked tokens, which will unlock progressively. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); return mint(_to, _amount); } /** * @dev Mint timelocked tokens. * @param _to The address that will receieve the minted locked tokens. * @param _amount The amount of tokens to mint. * @param _releaseTime The token release time as timestamp from Unix epoch. * @return A boolean that indicates if the operation was successful. */ /*function mintTimelocked(address _to, uint256 _amount, uint256 _releaseTime) public onlyOwner canMint returns (TokenTimelock tokenTimelock) { TokenTimelock timelock = new TokenTimelock(this, _to, _releaseTime); mint(timelock, _amount); return timelock; }*/ /** * @dev Mint vested tokens. * @param _to The address that will receieve the minted vested tokens. * @param _amount The amount of tokens to mint. * @param _startTime When the vesting starts as timestamp in seconds from Unix epoch. * @param _duration The duration in seconds of the period in which the tokens will vest. * @return A boolean that indicates if the operation was successful. */ /*function mintVested(address _to, uint256 _amount, uint256 _startTime, uint256 _duration) public onlyOwner canMint returns (TokenVesting tokenVesting) { TokenVesting vesting = new TokenVesting(_to, _startTime, 0, _duration, true); mint(vesting, _amount); return vesting; }*/ /** * @dev Release vested tokens to beneficiary. * @param _vesting The token vesting to release. */ /*function releaseVested(TokenVesting _vesting) public { require(_vesting != address(0)); _vesting.release(this); }*/ /** * @dev Revoke vested tokens. Just the token can revoke because it is the vesting owner. * @param _vesting The token vesting to revoke. */ /*function revokeVested(TokenVesting _vesting) public onlyOwner { require(_vesting != address(0)); _vesting.revoke(this); }*/ } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: contracts/NokuCustomService.sol contract NokuCustomService is Pausable { using AddressUtils for address; event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan); // The pricing plan determining the fee to be paid in NOKU tokens by customers NokuPricingPlan public pricingPlan; constructor(address _pricingPlan) internal { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); pricingPlan = NokuPricingPlan(_pricingPlan); } function setPricingPlan(address _pricingPlan) public onlyOwner { require(_pricingPlan.isContract(), "_pricingPlan is not contract"); require(NokuPricingPlan(_pricingPlan) != pricingPlan, "_pricingPlan equal to current"); pricingPlan = NokuPricingPlan(_pricingPlan); emit LogPricingPlanChanged(msg.sender, _pricingPlan); } } // File: contracts/NokuCustomERC20Service.sol /** * @dev The NokuCustomERC2Service contract . */ contract NokuCustomERC20Service is NokuCustomService { event LogNokuCustomERC20ServiceCreated(address caller, address indexed pricingPlan); uint256 public constant CREATE_AMOUNT = 1 * 10**18; uint8 public constant DECIMALS = 18; bytes32 public constant CUSTOM_ERC20_CREATE_SERVICE_NAME = "NokuCustomERC20.create"; constructor(address _pricingPlan) NokuCustomService(_pricingPlan) public { emit LogNokuCustomERC20ServiceCreated(msg.sender, _pricingPlan); } // TODO: REMOVE function createCustomToken(string _name, string _symbol, uint8 /*_decimals*/) public returns(NokuCustomERC20 customToken) { customToken = new NokuCustomERC20( _name, _symbol, DECIMALS, block.number, block.number, pricingPlan, owner ); // Transfer NokuCustomERC20 ownership to the client customToken.transferOwnership(msg.sender); require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); } function createCustomToken( string _name, string _symbol, uint8 /*_decimals*/, uint256 transferableFromBlock, uint256 lockEndBlock ) public returns(NokuCustomERC20 customToken) { customToken = new NokuCustomERC20( _name, _symbol, DECIMALS, transferableFromBlock, lockEndBlock, pricingPlan, owner ); // Transfer NokuCustomERC20 ownership to the client customToken.transferOwnership(msg.sender); require(pricingPlan.payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, CREATE_AMOUNT, msg.sender), "fee payment failed"); } }
Mint new locked tokens, which will unlock progressively. _to The address that will receieve the minted locked tokens. _amount The amount of tokens to mint. return A boolean that indicates if the operation was successful./
function mintLocked(address _to, uint256 _amount) public onlyOwner canMint returns(bool minted) { initiallyLockedBalanceOf[_to] = initiallyLockedBalanceOf[_to].add(_amount); return mint(_to, _amount); }
12,923,031
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: node_modules\@openzeppelin\contracts-ethereum-package\contracts\Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: node_modules\@openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: node_modules\@openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\@openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol pragma solidity ^0.6.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 {ERC20MinterPauser}. * * 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ 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; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf(account); } function _balanceOf(address account) internal view virtual returns (uint256) { } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin\contracts-ethereum-package\contracts\access\Ownable.sol pragma solidity ^0.6.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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts\RajaCoin.sol pragma solidity ^0.6.0; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract StakingWallet is Initializable, ContextUpgradeSafe, OwnableUpgradeSafe { using SafeMath for uint256; using Address for address; event Staked(address beneficiary, uint256 index, uint256 amount); event Released(address beneficiary, uint256 index, uint256 amount); event DailyBonused(address beneficiary, uint256 index, uint256 amount); struct StakingBalance { uint256 amount; uint256 bonusAmount; uint256 startDate; uint256 endDate; uint256 totalBonusReleased; bool isActive; } uint256 public totalStakingBalance; mapping(address => StakingBalance[]) public userStakingBalances; function __StakingWallet_init() internal initializer { __Context_init_unchained(); __StakingWallet_init_unchained(); } function userStakingBalancesLength(address _user) public view returns (uint256) { return userStakingBalances[_user].length; } function __StakingWallet_init_unchained() internal initializer { __Ownable_init_unchained(); } function staking(address _beneficiary, uint256 _amount, uint256 _bonus, uint256 _durationDays) public onlyOwner { require(_beneficiary != address(0), 'invalid beneficiary address'); require(_amount > 0, 'staking amount should be greater than zero'); require(_bonus > 0, 'bonus amount should be greater than zero'); _stakingBalance(_beneficiary, _amount); totalStakingBalance = totalStakingBalance.add(_amount); userStakingBalances[_beneficiary].push(StakingBalance(_amount, _bonus, now, now.add(_durationDays.mul(86400)), 0, true)); emit Staked(_beneficiary, userStakingBalances[_beneficiary].length - 1, _amount); } function release(address _beneficiary, uint256 _index) public onlyOwner { require(_beneficiary != address(0), 'invalid beneficiary address'); require(userStakingBalances[_beneficiary][_index].isActive, 'staking balance not active'); require(userStakingBalances[_beneficiary][_index].endDate <= now, 'still on staking period'); uint256 balanceReleased = userStakingBalances[_beneficiary][_index].amount; _releaseStakingBalance(_beneficiary, balanceReleased); totalStakingBalance = totalStakingBalance.sub(balanceReleased); emit Released(_beneficiary, _index, balanceReleased); } function transferBonus(address _beneficiary, uint256 _index, uint256 _bonusAmountReleased) public onlyOwner { require(userStakingBalances[_beneficiary][_index].totalBonusReleased.add(_bonusAmountReleased) <= userStakingBalances[_beneficiary][_index].bonusAmount, 'Exceed bonus amount'); _transferBonus(_beneficiary, _bonusAmountReleased); userStakingBalances[_beneficiary][_index].totalBonusReleased = userStakingBalances[_beneficiary][_index].totalBonusReleased.add(_bonusAmountReleased); emit DailyBonused(_beneficiary, _index, _bonusAmountReleased); } function _stakingBalance(address _payer, uint256 _amount) internal virtual { } function _releaseStakingBalance(address _beneficiary, uint256 _amount) internal virtual { } function _transferBonus(address _beneficiary, uint256 _amount) internal virtual { } uint256[49] private __gap; } contract RajaCoin is Initializable, ContextUpgradeSafe, OwnableUpgradeSafe, ERC20UpgradeSafe, StakingWallet { using SafeMath for uint256; using Address for address; address public walletBonus; address public oldContract; //config uint256 public cap; address public feeReceiver; mapping(address => bool) public isBalancesMigrated; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __RajaToken_init(uint256 _cap) public initializer { __Context_init_unchained(); __ERC20_init_unchained('RAJACOIN', 'RAJA'); __Ownable_init_unchained(); __StakingWallet_init_unchained(); __RajaToken_init_unchained(_cap); } function __RajaToken_init_unchained(uint256 _cap) internal initializer { require(_cap > 0, "RajaCoin: cap is 0"); cap = _cap; _mint(_msgSender(), cap); } function _balanceOf(address account) internal view override returns (uint256) { if (isBalancesMigrated[account] || account == owner() || oldContract == address(0)) { return _balances[account]; } return IERC20(oldContract).balanceOf(account); } function _transfer(address sender, address recipient, uint256 amount) internal override { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); //Migrating balance sender from old contract if (!isBalancesMigrated[sender] && sender != owner() && oldContract != address(0)) { _balances[sender] = balanceOf(sender); _balances[owner()] = _balances[owner()].sub(balanceOf(sender)); isBalancesMigrated[sender] = true; } //Migrating balance recipient from old contract if (!isBalancesMigrated[recipient] && recipient != owner() && oldContract != address(0)) { _balances[recipient] = balanceOf(recipient); _balances[owner()] = _balances[owner()].sub(balanceOf(recipient)); isBalancesMigrated[recipient] = true; } _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev special tranfer only owner can trigger this function */ function rajaTransfer(address sender, address recipient, uint256 amount, uint256 fee) public onlyOwner returns (bool) { require(feeReceiver != address(0), 'fee receiver address not registed'); _beforeTokenTransfer(sender, recipient, amount.add(fee)); _transfer(sender, recipient, amount); if (fee > 0) { _transfer(sender, feeReceiver, fee); } return true; } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - check if balance of sender is sufficient for transfer */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (from != address(0)) { // When minting tokens require(balanceOf(from) >= amount, "RajaCoin: insufficient sender balance"); } } function setWalletBonus(address _walletBonus) public onlyOwner { walletBonus = _walletBonus; } function setOldContract(address _oldContract) public onlyOwner { oldContract = _oldContract; } function _stakingBalance(address _beneficiary, uint256 _amount) internal override { _transfer(owner(), address(this), _amount); } function _releaseStakingBalance(address _beneficiary, uint256 _amount) internal override { _transfer(address(this), _beneficiary, _amount); } function _transferBonus(address _beneficiary, uint256 _amount) internal override { _transfer(walletBonus, _beneficiary, _amount); } function setFeeReceiver(address _feeReceiver) public onlyOwner { feeReceiver = _feeReceiver; } uint256[49] private __gap; }
Sets the value of the `cap`. This value is immutable, it can only be set once during construction./
function __RajaToken_init(uint256 _cap) public initializer { __Context_init_unchained(); __ERC20_init_unchained('RAJACOIN', 'RAJA'); __Ownable_init_unchained(); __StakingWallet_init_unchained(); __RajaToken_init_unchained(_cap); }
10,199,129
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: IBank interface IBank { /// The governor adds a new bank gets added to the system. event AddBank(address token, address cToken); /// The governor sets the address of the oracle smart contract. event SetOracle(address oracle); /// The governor sets the basis point fee of the bank. event SetFeeBps(uint feeBps); /// The governor withdraw tokens from the reserve of a bank. event WithdrawReserve(address user, address token, uint amount); /// Someone borrows tokens from a bank via a spell caller. event Borrow(uint positionId, address caller, address token, uint amount, uint share); /// Someone repays tokens to a bank via a spell caller. event Repay(uint positionId, address caller, address token, uint amount, uint share); /// Someone puts tokens as collateral via a spell caller. event PutCollateral(uint positionId, address caller, address token, uint id, uint amount); /// Someone takes tokens from collateral via a spell caller. event TakeCollateral(uint positionId, address caller, address token, uint id, uint amount); /// Someone calls liquidatation on a position, paying debt and taking collateral tokens. event Liquidate( uint positionId, address liquidator, address debtToken, uint amount, uint share, uint bounty ); /// @dev Return the current position while under execution. function POSITION_ID() external view returns (uint); /// @dev Return the current target while under execution. function SPELL() external view returns (address); /// @dev Return the current executor (the owner of the current position). function EXECUTOR() external view returns (address); /// @dev Return bank information for the given token. function getBankInfo(address token) external view returns ( bool isListed, address cToken, uint reserve, uint totalDebt, uint totalShare ); /// @dev Return position information for the given position id. function getPositionInfo(uint positionId) external view returns ( address owner, address collToken, uint collId, uint collateralSize ); /// @dev Return the borrow balance for given positon and token without trigger interest accrual. function borrowBalanceStored(uint positionId, address token) external view returns (uint); /// @dev Trigger interest accrual and return the current borrow balance. function borrowBalanceCurrent(uint positionId, address token) external returns (uint); /// @dev Borrow tokens from the bank. function borrow(address token, uint amount) external; /// @dev Repays tokens to the bank. function repay(address token, uint amountCall) external; /// @dev Transmit user assets to the spell. function transmit(address token, uint amount) external; /// @dev Put more collateral for users. function putCollateral( address collToken, uint collId, uint amountCall ) external; /// @dev Take some collateral back. function takeCollateral( address collToken, uint collId, uint amount ) external; /// @dev Liquidate a position. function liquidate( uint positionId, address debtToken, uint amountCall ) external; function getBorrowETHValue(uint positionId) external view returns (uint); function accrue(address token) external; function nextPositionId() external view returns (uint); /// @dev Return current position information. function getCurrentPositionInfo() external view returns ( address owner, address collToken, uint collId, uint collateralSize ); function support(address token) external view returns (bool); } // Part: IERC20Wrapper interface IERC20Wrapper { /// @dev Return the underlying ERC-20 for the given ERC-1155 token id. function getUnderlyingToken(uint id) external view returns (address); /// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112. function getUnderlyingRate(uint id) external view returns (uint); } // Part: IMasterChef interface IMasterChef { function sushi() external view returns (address); function poolInfo(uint pid) external view returns ( address lpToken, uint allocPoint, uint lastRewardBlock, uint accSushiPerShare ); function deposit(uint pid, uint amount) external; function withdraw(uint pid, uint amount) external; } // Part: IUniswapV2Factory // https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Factory.sol 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; } // Part: IUniswapV2Pair // https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/interfaces/IUniswapV2Pair.sol 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; } // Part: IUniswapV2Router01 // https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol 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); } // Part: IUniswapV2Router02 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; } // Part: IWETH interface IWETH { function balanceOf(address user) external returns (uint); function approve(address to, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function deposit() external payable; function withdraw(uint) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // Part: HomoraMath library HomoraMath { using SafeMath for uint; function divCeil(uint lhs, uint rhs) internal pure returns (uint) { return lhs.add(rhs).sub(1) / rhs; } function fmul(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(rhs) / (2**112); } function fdiv(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(2**112) / rhs; } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // Part: OpenZeppelin/[email protected]/IERC1155 /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // Part: OpenZeppelin/[email protected]/IERC1155Receiver /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // Part: OpenZeppelin/[email protected]/Initializable /** * @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 !Address.isContract(address(this)); } } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: Governable contract Governable is Initializable { event SetGovernor(address governor); event SetPendingGovernor(address pendingGovernor); event AcceptGovernor(address governor); address public governor; // The current governor. address public pendingGovernor; // The address pending to become the governor once accepted. bytes32[64] _gap; // reserve space for upgrade modifier onlyGov() { require(msg.sender == governor, 'not the governor'); _; } /// @dev Initialize using msg.sender as the first governor. function __Governable__init() internal initializer { governor = msg.sender; pendingGovernor = address(0); emit SetGovernor(msg.sender); } /// @dev Set the pending governor, which will be the governor once accepted. /// @param _pendingGovernor The address to become the pending governor. function setPendingGovernor(address _pendingGovernor) external onlyGov { pendingGovernor = _pendingGovernor; emit SetPendingGovernor(_pendingGovernor); } /// @dev Accept to become the new governor. Must be called by the pending governor. function acceptGovernor() external { require(msg.sender == pendingGovernor, 'not the pending governor'); pendingGovernor = address(0); governor = msg.sender; emit AcceptGovernor(msg.sender); } } // Part: IWERC20 interface IWERC20 is IERC1155, IERC20Wrapper { /// @dev Return the underlying ERC20 balance for the user. function balanceOfERC20(address token, address user) external view returns (uint); /// @dev Mint ERC1155 token for the given ERC20 token. function mint(address token, uint amount) external; /// @dev Burn ERC1155 token to redeem ERC20 token back. function burn(address token, uint amount) external; } // Part: IWMasterChef interface IWMasterChef is IERC1155, IERC20Wrapper { /// @dev Mint ERC1155 token for the given ERC20 token. function mint(uint pid, uint amount) external returns (uint id); /// @dev Burn ERC1155 token to redeem ERC20 token back. function burn(uint id, uint amount) external returns (uint pid); function sushi() external returns (IERC20); function decodeId(uint id) external pure returns (uint, uint); function chef() external view returns (IMasterChef); } // Part: OpenZeppelin/[email protected]/ERC1155Receiver /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() internal { _registerInterface( ERC1155Receiver(address(0)).onERC1155Received.selector ^ ERC1155Receiver(address(0)).onERC1155BatchReceived.selector ); } } // Part: ERC1155NaiveReceiver contract ERC1155NaiveReceiver is ERC1155Receiver { bytes32[64] __gap; // reserve space for upgrade function onERC1155Received( address, /* operator */ address, /* from */ uint, /* id */ uint, /* value */ bytes calldata /* data */ ) external override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, /* operator */ address, /* from */ uint[] calldata, /* ids */ uint[] calldata, /* values */ bytes calldata /* data */ ) external override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // Part: BasicSpell abstract contract BasicSpell is ERC1155NaiveReceiver { using SafeERC20 for IERC20; IBank public immutable bank; IWERC20 public immutable werc20; address public immutable weth; mapping(address => mapping(address => bool)) public approved; // Mapping from token to (mapping from spender to approve status) constructor( IBank _bank, address _werc20, address _weth ) public { bank = _bank; werc20 = IWERC20(_werc20); weth = _weth; ensureApprove(_weth, address(_bank)); IWERC20(_werc20).setApprovalForAll(address(_bank), true); } /// @dev Ensure that the spell has approved the given spender to spend all of its tokens. /// @param token The token to approve. /// @param spender The spender to allow spending. /// NOTE: This is safe because spell is never built to hold fund custody. function ensureApprove(address token, address spender) internal { if (!approved[token][spender]) { IERC20(token).safeApprove(spender, uint(-1)); approved[token][spender] = true; } } /// @dev Internal call to convert msg.value ETH to WETH inside the contract. function doTransmitETH() internal { if (msg.value > 0) { IWETH(weth).deposit{value: msg.value}(); } } /// @dev Internal call to transmit tokens from the bank if amount is positive. /// @param token The token to perform the transmit action. /// @param amount The amount to transmit. /// @notice Do not use `amount` input argument to handle the received amount. function doTransmit(address token, uint amount) internal { if (amount > 0) { bank.transmit(token, amount); } } /// @dev Internal call to refund tokens to the current bank executor. /// @param token The token to perform the refund action. function doRefund(address token) internal { uint balance = IERC20(token).balanceOf(address(this)); if (balance > 0) { IERC20(token).safeTransfer(bank.EXECUTOR(), balance); } } /// @dev Internal call to refund all WETH to the current executor as native ETH. function doRefundETH() internal { uint balance = IWETH(weth).balanceOf(address(this)); if (balance > 0) { IWETH(weth).withdraw(balance); (bool success, ) = bank.EXECUTOR().call{value: balance}(new bytes(0)); require(success, 'refund ETH failed'); } } /// @dev Internal call to borrow tokens from the bank on behalf of the current executor. /// @param token The token to borrow from the bank. /// @param amount The amount to borrow. /// @notice Do not use `amount` input argument to handle the received amount. function doBorrow(address token, uint amount) internal { if (amount > 0) { bank.borrow(token, amount); } } /// @dev Internal call to repay tokens to the bank on behalf of the current executor. /// @param token The token to repay to the bank. /// @param amount The amount to repay. function doRepay(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(bank)); bank.repay(token, amount); } } /// @dev Internal call to put collateral tokens in the bank. /// @param token The token to put in the bank. /// @param amount The amount to put in the bank. function doPutCollateral(address token, uint amount) internal { if (amount > 0) { ensureApprove(token, address(werc20)); werc20.mint(token, amount); bank.putCollateral(address(werc20), uint(token), amount); } } /// @dev Internal call to take collateral tokens from the bank. /// @param token The token to take back. /// @param amount The amount to take back. function doTakeCollateral(address token, uint amount) internal { if (amount > 0) { if (amount == uint(-1)) { (, , , amount) = bank.getCurrentPositionInfo(); } bank.takeCollateral(address(werc20), uint(token), amount); werc20.burn(token, amount); } } /// @dev Fallback function. Can only receive ETH from WETH contract. receive() external payable { require(msg.sender == weth, 'ETH must come from WETH'); } } // Part: WhitelistSpell contract WhitelistSpell is BasicSpell, Governable { mapping(address => bool) public whitelistedLpTokens; // mapping from lp token to whitelist status constructor( IBank _bank, address _werc20, address _weth ) public BasicSpell(_bank, _werc20, _weth) { __Governable__init(); } /// @dev Set whitelist LP token statuses for spell /// @param lpTokens LP tokens to set whitelist statuses /// @param statuses Whitelist statuses function setWhitelistLPTokens(address[] calldata lpTokens, bool[] calldata statuses) external onlyGov { require(lpTokens.length == statuses.length, 'lpTokens & statuses length mismatched'); for (uint idx = 0; idx < lpTokens.length; idx++) { if (statuses[idx]) { require(bank.support(lpTokens[idx]), 'oracle not support lp token'); } whitelistedLpTokens[lpTokens[idx]] = statuses[idx]; } } } // File: SushiswapSpellV1.sol contract SushiswapSpellV1 is WhitelistSpell { using SafeMath for uint; using HomoraMath for uint; IUniswapV2Factory public immutable factory; // Sushiswap factory IUniswapV2Router02 public immutable router; // Sushiswap router mapping(address => mapping(address => address)) public pairs; // Mapping from tokenA to (mapping from tokenB to LP token) IWMasterChef public immutable wmasterchef; // Wrapped masterChef address public immutable sushi; // Sushi token address constructor( IBank _bank, address _werc20, IUniswapV2Router02 _router, address _wmasterchef ) public WhitelistSpell(_bank, _werc20, _router.WETH()) { router = _router; factory = IUniswapV2Factory(_router.factory()); wmasterchef = IWMasterChef(_wmasterchef); IWMasterChef(_wmasterchef).setApprovalForAll(address(_bank), true); sushi = address(IWMasterChef(_wmasterchef).sushi()); } /// @dev Return the LP token for the token pairs (can be in any order) /// @param tokenA Token A to get LP token /// @param tokenB Token B to get LP token function getAndApprovePair(address tokenA, address tokenB) public returns (address) { address lp = pairs[tokenA][tokenB]; if (lp == address(0)) { lp = factory.getPair(tokenA, tokenB); require(lp != address(0), 'no lp token'); ensureApprove(tokenA, address(router)); ensureApprove(tokenB, address(router)); ensureApprove(lp, address(router)); pairs[tokenA][tokenB] = lp; pairs[tokenB][tokenA] = lp; } return lp; } /// @dev Compute optimal deposit amount /// @param amtA amount of token A desired to deposit /// @param amtB amount of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve function optimalDeposit( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint swapAmt, bool isReversed) { if (amtA.mul(resB) >= amtB.mul(resA)) { swapAmt = _optimalDepositA(amtA, amtB, resA, resB); isReversed = false; } else { swapAmt = _optimalDepositA(amtB, amtA, resB, resA); isReversed = true; } } /// @dev Compute optimal deposit amount helper. /// @param amtA amount of token A desired to deposit /// @param amtB amount of token B desired to deposit /// @param resA amount of token A in reserve /// @param resB amount of token B in reserve /// Formula: https://blog.alphafinance.io/byot/ function _optimalDepositA( uint amtA, uint amtB, uint resA, uint resB ) internal pure returns (uint) { require(amtA.mul(resB) >= amtB.mul(resA), 'Reversed'); uint a = 997; uint b = uint(1997).mul(resA); uint _c = (amtA.mul(resB)).sub(amtB.mul(resA)); uint c = _c.mul(1000).div(amtB.add(resB)).mul(resA); uint d = a.mul(c).mul(4); uint e = HomoraMath.sqrt(b.mul(b).add(d)); uint numerator = e.sub(b); uint denominator = a.mul(2); return numerator.div(denominator); } struct Amounts { uint amtAUser; // Supplied tokenA amount uint amtBUser; // Supplied tokenB amount uint amtLPUser; // Supplied LP token amount uint amtABorrow; // Borrow tokenA amount uint amtBBorrow; // Borrow tokenB amount uint amtLPBorrow; // Borrow LP token amount uint amtAMin; // Desired tokenA amount (slippage control) uint amtBMin; // Desired tokenB amount (slippage control) } /// @dev Add liquidity to Sushiswap pool /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to supply, borrow, and get. function addLiquidityInternal( address tokenA, address tokenB, Amounts calldata amt, address lp ) internal { require(whitelistedLpTokens[lp], 'lp token not whitelisted'); // 1. Get user input amounts doTransmitETH(); doTransmit(tokenA, amt.amtAUser); doTransmit(tokenB, amt.amtBUser); doTransmit(lp, amt.amtLPUser); // 2. Borrow specified amounts doBorrow(tokenA, amt.amtABorrow); doBorrow(tokenB, amt.amtBBorrow); doBorrow(lp, amt.amtLPBorrow); // 3. Calculate optimal swap amount uint swapAmt; bool isReversed; { uint amtA = IERC20(tokenA).balanceOf(address(this)); uint amtB = IERC20(tokenB).balanceOf(address(this)); uint resA; uint resB; if (IUniswapV2Pair(lp).token0() == tokenA) { (resA, resB, ) = IUniswapV2Pair(lp).getReserves(); } else { (resB, resA, ) = IUniswapV2Pair(lp).getReserves(); } (swapAmt, isReversed) = optimalDeposit(amtA, amtB, resA, resB); } // 4. Swap optimal amount if (swapAmt > 0) { address[] memory path = new address[](2); (path[0], path[1]) = isReversed ? (tokenB, tokenA) : (tokenA, tokenB); router.swapExactTokensForTokens(swapAmt, 0, path, address(this), block.timestamp); } // 5. Add liquidity uint balA = IERC20(tokenA).balanceOf(address(this)); uint balB = IERC20(tokenB).balanceOf(address(this)); if (balA > 0 || balB > 0) { router.addLiquidity( tokenA, tokenB, balA, balB, amt.amtAMin, amt.amtBMin, address(this), block.timestamp ); } } /// @dev Add liquidity to Sushiswap pool, with no staking rewards (use WERC20 wrapper) /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to supply, borrow, and get. function addLiquidityWERC20( address tokenA, address tokenB, Amounts calldata amt ) external payable { address lp = getAndApprovePair(tokenA, tokenB); // 1-5. add liquidity addLiquidityInternal(tokenA, tokenB, amt, lp); // 6. Put collateral doPutCollateral(lp, IERC20(lp).balanceOf(address(this))); // 7. Refund leftovers to users doRefundETH(); doRefund(tokenA); doRefund(tokenB); } /// @dev Add liquidity to Sushiswap pool, with staking to masterChef /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to supply, borrow, and get. /// @param pid Pool id function addLiquidityWMasterChef( address tokenA, address tokenB, Amounts calldata amt, uint pid ) external payable { address lp = getAndApprovePair(tokenA, tokenB); (address lpToken, , , ) = wmasterchef.chef().poolInfo(pid); require(lpToken == lp, 'incorrect lp token'); // 1-5. add liquidity addLiquidityInternal(tokenA, tokenB, amt, lp); // 6. Take out collateral (, address collToken, uint collId, uint collSize) = bank.getCurrentPositionInfo(); if (collSize > 0) { (uint decodedPid, ) = wmasterchef.decodeId(collId); require(pid == decodedPid, 'incorrect pid'); require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched'); bank.takeCollateral(address(wmasterchef), collId, collSize); wmasterchef.burn(collId, collSize); } // 7. Put collateral ensureApprove(lp, address(wmasterchef)); uint amount = IERC20(lp).balanceOf(address(this)); uint id = wmasterchef.mint(pid, amount); bank.putCollateral(address(wmasterchef), id, amount); // 8. Refund leftovers to users doRefundETH(); doRefund(tokenA); doRefund(tokenB); // 9. Refund sushi doRefund(sushi); } struct RepayAmounts { uint amtLPTake; // Take out LP token amount (from Homora) uint amtLPWithdraw; // Withdraw LP token amount (back to caller) uint amtARepay; // Repay tokenA amount uint amtBRepay; // Repay tokenB amount uint amtLPRepay; // Repay LP token amount uint amtAMin; // Desired tokenA amount uint amtBMin; // Desired tokenB amount } /// @dev Remove liquidity from Sushiswap pool /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to take out, withdraw, repay, and get. function removeLiquidityInternal( address tokenA, address tokenB, RepayAmounts calldata amt, address lp ) internal { require(whitelistedLpTokens[lp], 'lp token not whitelisted'); uint positionId = bank.POSITION_ID(); uint amtARepay = amt.amtARepay; uint amtBRepay = amt.amtBRepay; uint amtLPRepay = amt.amtLPRepay; // 2. Compute repay amount if MAX_INT is supplied (max debt) if (amtARepay == uint(-1)) { amtARepay = bank.borrowBalanceCurrent(positionId, tokenA); } if (amtBRepay == uint(-1)) { amtBRepay = bank.borrowBalanceCurrent(positionId, tokenB); } if (amtLPRepay == uint(-1)) { amtLPRepay = bank.borrowBalanceCurrent(positionId, lp); } // 3. Compute amount to actually remove uint amtLPToRemove = IERC20(lp).balanceOf(address(this)).sub(amt.amtLPWithdraw); // 4. Remove liquidity uint amtA; uint amtB; if (amtLPToRemove > 0) { (amtA, amtB) = router.removeLiquidity( tokenA, tokenB, amtLPToRemove, 0, 0, address(this), block.timestamp ); } // 5. MinimizeTrading uint amtADesired = amtARepay.add(amt.amtAMin); uint amtBDesired = amtBRepay.add(amt.amtBMin); if (amtA < amtADesired && amtB > amtBDesired) { address[] memory path = new address[](2); (path[0], path[1]) = (tokenB, tokenA); router.swapTokensForExactTokens( amtADesired.sub(amtA), amtB.sub(amtBDesired), path, address(this), block.timestamp ); } else if (amtA > amtADesired && amtB < amtBDesired) { address[] memory path = new address[](2); (path[0], path[1]) = (tokenA, tokenB); router.swapTokensForExactTokens( amtBDesired.sub(amtB), amtA.sub(amtADesired), path, address(this), block.timestamp ); } // 6. Repay doRepay(tokenA, amtARepay); doRepay(tokenB, amtBRepay); doRepay(lp, amtLPRepay); // 7. Slippage control require(IERC20(tokenA).balanceOf(address(this)) >= amt.amtAMin); require(IERC20(tokenB).balanceOf(address(this)) >= amt.amtBMin); require(IERC20(lp).balanceOf(address(this)) >= amt.amtLPWithdraw); // 8. Refund leftover doRefundETH(); doRefund(tokenA); doRefund(tokenB); doRefund(lp); } /// @dev Remove liquidity from Sushiswap pool, with no staking rewards (use WERC20 wrapper) /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to take out, withdraw, repay, and get. function removeLiquidityWERC20( address tokenA, address tokenB, RepayAmounts calldata amt ) external { address lp = getAndApprovePair(tokenA, tokenB); // 1. Take out collateral doTakeCollateral(lp, amt.amtLPTake); // 2-8. remove liquidity removeLiquidityInternal(tokenA, tokenB, amt, lp); } /// @dev Remove liquidity from Sushiswap pool, from masterChef staking /// @param tokenA Token A for the pair /// @param tokenB Token B for the pair /// @param amt Amounts of tokens to take out, withdraw, repay, and get. function removeLiquidityWMasterChef( address tokenA, address tokenB, RepayAmounts calldata amt ) external { address lp = getAndApprovePair(tokenA, tokenB); (, address collToken, uint collId, ) = bank.getCurrentPositionInfo(); require(IWMasterChef(collToken).getUnderlyingToken(collId) == lp, 'incorrect underlying'); require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched'); // 1. Take out collateral bank.takeCollateral(address(wmasterchef), collId, amt.amtLPTake); wmasterchef.burn(collId, amt.amtLPTake); // 2-8. remove liquidity removeLiquidityInternal(tokenA, tokenB, amt, lp); // 9. Refund sushi doRefund(sushi); } /// @dev Harvest SUSHI reward tokens to in-exec position's owner function harvestWMasterChef() external { (, address collToken, uint collId, ) = bank.getCurrentPositionInfo(); (uint pid, ) = wmasterchef.decodeId(collId); address lp = wmasterchef.getUnderlyingToken(collId); require(whitelistedLpTokens[lp], 'lp token not whitelisted'); require(collToken == address(wmasterchef), 'collateral token & wmasterchef mismatched'); // 1. Take out collateral bank.takeCollateral(address(wmasterchef), collId, uint(-1)); wmasterchef.burn(collId, uint(-1)); // 2. put collateral uint amount = IERC20(lp).balanceOf(address(this)); ensureApprove(lp, address(wmasterchef)); uint id = wmasterchef.mint(pid, amount); bank.putCollateral(address(wmasterchef), id, amount); // 3. Refund sushi doRefund(sushi); } }
Remove liquidity from Sushiswap pool tokenA Token A for the pair tokenB Token B for the pair amt Amounts of tokens to take out, withdraw, repay, and get. 2. Compute repay amount if MAX_INT is supplied (max debt)
function removeLiquidityInternal( address tokenA, address tokenB, RepayAmounts calldata amt, address lp ) internal { require(whitelistedLpTokens[lp], 'lp token not whitelisted'); uint positionId = bank.POSITION_ID(); uint amtARepay = amt.amtARepay; uint amtBRepay = amt.amtBRepay; uint amtLPRepay = amt.amtLPRepay; if (amtARepay == uint(-1)) { amtARepay = bank.borrowBalanceCurrent(positionId, tokenA); } if (amtBRepay == uint(-1)) { amtBRepay = bank.borrowBalanceCurrent(positionId, tokenB); } if (amtLPRepay == uint(-1)) { amtLPRepay = bank.borrowBalanceCurrent(positionId, lp); } uint amtB; if (amtLPToRemove > 0) { (amtA, amtB) = router.removeLiquidity( tokenA, tokenB, amtLPToRemove, 0, 0, address(this), block.timestamp ); } uint amtBDesired = amtBRepay.add(amt.amtBMin); if (amtA < amtADesired && amtB > amtBDesired) { address[] memory path = new address[](2); (path[0], path[1]) = (tokenB, tokenA); router.swapTokensForExactTokens( amtADesired.sub(amtA), amtB.sub(amtBDesired), path, address(this), block.timestamp ); address[] memory path = new address[](2); (path[0], path[1]) = (tokenA, tokenB); router.swapTokensForExactTokens( amtBDesired.sub(amtB), amtA.sub(amtADesired), path, address(this), block.timestamp ); } doRepay(tokenB, amtBRepay); doRepay(lp, amtLPRepay); require(IERC20(tokenB).balanceOf(address(this)) >= amt.amtBMin); require(IERC20(lp).balanceOf(address(this)) >= amt.amtLPWithdraw); doRefund(tokenA); doRefund(tokenB); doRefund(lp); }
6,085,275
./partial_match/1313161554/0xE17B0d13926F03C0a9C2d6185B505C253E7cDb1d/sources/_contracts/abstract/ReaperBaseStrategyv2.sol
updates the call fee, treasury fee, and strategist fee call Fee + treasury Fee must add up to PERCENT_DIVISOR strategist fee is expressed as % of the treasury fee and must be no more than STRATEGIST_MAX_FEE only DEFAULT_ADMIN_ROLE./
function updateFees( uint256 _callFee, uint256 _treasuryFee, uint256 _strategistFee ) external returns (bool) { _atLeastRole(DEFAULT_ADMIN_ROLE); require(_callFee + _treasuryFee == PERCENT_DIVISOR, 'sum != PERCENT_DIVISOR'); require(_strategistFee <= STRATEGIST_MAX_FEE, 'strategist fee > STRATEGIST_MAX_FEE'); callFee = _callFee; treasuryFee = _treasuryFee; strategistFee = _strategistFee; emit FeesUpdated(callFee, treasuryFee, strategistFee); return true; }
16,912,196
pragma solidity ^0.6.6; // SPDX-License-Identifier: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT /** * @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 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 /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT /** * @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); } } } } // SPDX-License-Identifier: MIT /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received( address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data ) external returns (bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data ) external returns (bytes4); /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // SPDX-License-Identifier: MIT /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 internal constant ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 internal constant ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping(address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping(address => mapping(address => bool)) internal operators; // Events event TransferSingle( address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount ); event TransferBatch( address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts ); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); event URI(string _uri, uint256 indexed _id); /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) public { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount >= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) public { // Requirements require( (msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR" ); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount ) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received( address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts ) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived(msg.sender, _from, _ids, _amounts, _data); require( retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE" ); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public view virtual returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC165 = 0x01ffc9a7; /** * INTERFACE_SIGNATURE_ERC1155 = * bytes4(keccak256("safeTransferFrom(address,address,uint256,uint256,bytes)")) ^ * bytes4(keccak256("safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)")) ^ * bytes4(keccak256("balanceOf(address,uint256)")) ^ * bytes4(keccak256("balanceOfBatch(address[],uint256[])")) ^ * bytes4(keccak256("setApprovalForAll(address,bool)")) ^ * bytes4(keccak256("isApprovedForAll(address,address)")); */ bytes4 private constant INTERFACE_SIGNATURE_ERC1155 = 0xd9b67a26; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) external view override(IERC165) returns (bool) { if (_interfaceID == INTERFACE_SIGNATURE_ERC165 || _interfaceID == INTERFACE_SIGNATURE_ERC1155) { return true; } return false; } } // SPDX-License-Identifier: MIT /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata { // URI's default URI prefix string internal baseMetadataURI; event URI(string _uri, uint256 indexed _id); /***********************************| | Metadata Public Function s | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) public view virtual returns (string memory) { return string(abi.encodePacked(baseMetadataURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseMetadataURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will emit a specific URI log event for corresponding token * @param _tokenIDs IDs of the token corresponding to the _uris logged * @param _URIs The URIs of the specified _tokenIDs */ function _logURIs(uint256[] memory _tokenIDs, string[] memory _URIs) internal { require(_tokenIDs.length == _URIs.length, "ERC1155Metadata#_logURIs: INVALID_ARRAYS_LENGTH"); for (uint256 i = 0; i < _tokenIDs.length; i++) { emit URI(_URIs[i], _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseMetadataURI = _newBaseMetadataURI; } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = bytes1(uint8(48 + (ii % 10))); ii /= 10; } // Convert to string return string(bstr); } } // SPDX-License-Identifier: MIT /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint( address _to, uint256 _id, uint256 _amount, bytes memory _data ) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint( address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data ) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn( address _from, uint256 _id, uint256 _amount ) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn( address _from, uint256[] memory _ids, uint256[] memory _amounts ) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nBurn = _ids.length; // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: MIT /** * @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]; } } // SPDX-License-Identifier: MIT contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor() internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } // SPDX-License-Identifier: MIT abstract contract Proxy { event ReceivedEther(address indexed sender, uint256 amount); /** * @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 Tells the type of proxy (EIP 897) * @return Type of proxy, 2 for upgradeable proxy */ function proxyType() public pure virtual returns (uint256); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ fallback() external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } /** * @dev Receive Ether and generate a log event */ receive() external payable { emit ReceivedEther(msg.sender, msg.value); } } // SPDX-License-Identifier: MIT contract OwnedUpgradeabilityStorage is Proxy { // Current implementation address internal _implementation; // Owner of the contract address private _upgradeabilityOwner; /** * @dev Tells the address of the owner * @return the address of the owner */ function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } /** * @dev Sets the address of the owner */ function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view override returns (address) { return _implementation; } /** * @dev Tells the proxy type (EIP 897) * @return Proxy type, 2 for forwarding proxy */ function proxyType() public pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT contract OwnedUpgradeabilityProxy is OwnedUpgradeabilityStorage { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); /** * @dev Upgrades the implementation address * @param implementation representing the address of the new implementation to be set */ function _upgradeTo(address implementation) internal { require(_implementation != implementation); _implementation = implementation; emit Upgraded(implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the proxy owner * @return the address of the proxy owner */ function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(address implementation) public onlyProxyOwner { _upgradeTo(implementation); } /** * @dev Allows the upgradeability owner to upgrade the current implementation of the proxy * and delegatecall the new implementation for initialization. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(address implementation, bytes memory data) public payable onlyProxyOwner { upgradeTo(implementation); (bool result, ) = address(this).delegatecall(data); require(result); } } // SPDX-License-Identifier: MIT contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor( address owner, address initialImplementation, bytes memory callData ) public { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); (bool result, ) = initialImplementation.delegatecall(callData); require(result); } } // SPDX-License-Identifier: MIT contract ProxyRegistry is Ownable { /* DelegateProxy implementation contract. Must be initialized. */ address public delegateProxyImplementation; /* Authenticated proxies by user. */ mapping(address => OwnableDelegateProxy) public proxies; /* Contracts pending access. */ mapping(address => uint256) public pending; /* Contracts allowed to call those proxies. */ mapping(address => bool) public contracts; /* Delay period for adding an authenticated contract. This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO), a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have plenty of time to notice and transfer their assets. */ uint256 public DELAY_PERIOD = 2 weeks; /** * Start the process to enable access for specified contract. Subject to delay period. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function startGrantAuthentication(address addr) public onlyOwner { require(!contracts[addr] && pending[addr] == 0); pending[addr] = now; } /** * End the process to nable access for specified contract after delay period has passed. * * @dev ProxyRegistry owner only * @param addr Address to which to grant permissions */ function endGrantAuthentication(address addr) public onlyOwner { require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < now)); pending[addr] = 0; contracts[addr] = true; } /** * Revoke access for specified contract. Can be done instantly. * * @dev ProxyRegistry owner only * @param addr Address of which to revoke permissions */ function revokeAuthentication(address addr) public onlyOwner { contracts[addr] = false; } /** * Register a proxy contract with this registry * * @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy * @return proxy New AuthenticatedProxy contract */ function registerProxy() public returns (OwnableDelegateProxy proxy) { require(address(proxies[msg.sender]) == address(0)); proxy = new OwnableDelegateProxy( msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this)) ); proxies[msg.sender] = proxy; } } // SPDX-License-Identifier: MIT library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat( string memory _a, string memory _b, string memory _c, string memory _d, string memory _e ) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint256 k = 0; for (uint256 i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint256 i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint256 i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint256 i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint256 i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat( string memory _a, string memory _b, string memory _c, string memory _d ) internal pure returns (string memory) { return strConcat(_a, _b, _c, _d, ""); } function strConcat( string memory _a, string memory _b, string memory _c ) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; while (_i != 0) { bstr[k--] = bytes1(uint8(48 + (_i % 10))); _i /= 10; } return string(bstr); } } // SPDX-License-Identifier: MIT /** * @title WhitelistAdminRole * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts. */ contract WhitelistAdminRole is Context { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor() internal { _addWhitelistAdmin(_msgSender()); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } function isWhitelistAdmin(address account) public view returns (bool) { return _whitelistAdmins.has(account); } function addWhitelistAdmin(address account) public onlyWhitelistAdmin { _addWhitelistAdmin(account); } function renounceWhitelistAdmin() public { _removeWhitelistAdmin(_msgSender()); } function _addWhitelistAdmin(address account) internal { _whitelistAdmins.add(account); emit WhitelistAdminAdded(account); } function _removeWhitelistAdmin(address account) internal { _whitelistAdmins.remove(account); emit WhitelistAdminRemoved(account); } } // SPDX-License-Identifier: MIT /** * @title ERC1155Tradable * ERC1155Tradable - ERC1155 contract that whitelists an operator address, * has create and mint functionality, and supports useful standards from OpenZeppelin, like _exists(), name(), symbol(), and totalSupply() */ contract ERC1155Tradable is ERC1155, ERC1155MintBurn, ERC1155Metadata, Ownable, MinterRole, WhitelistAdminRole { using Strings for string; address proxyRegistryAddress; uint256 private _currentTokenID = 0; mapping(uint256 => address) public creators; mapping(uint256 => uint256) public tokenSupply; mapping(uint256 => uint256) public tokenMaxSupply; // Contract name string public name; // Contract symbol string public symbol; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) public { name = _name; symbol = _symbol; proxyRegistryAddress = _proxyRegistryAddress; } function removeWhitelistAdmin(address account) public onlyOwner { _removeWhitelistAdmin(account); } function removeMinter(address account) public onlyOwner { _removeMinter(account); } function uri(uint256 _id) public view override returns (string memory) { require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN"); return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id)); } /** * @dev Returns the total quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function totalSupply(uint256 _id) public view returns (uint256) { return tokenSupply[_id]; } /** * @dev Returns the max quantity for a token ID * @param _id uint256 ID of the token to query * @return amount of token in existence */ function maxSupply(uint256 _id) public view returns (uint256) { return tokenMaxSupply[_id]; } /** * @dev Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function setBaseMetadataURI(string memory _newBaseMetadataURI) public onlyWhitelistAdmin { _setBaseMetadataURI(_newBaseMetadataURI); } /** * @dev Creates a new token type and assigns _initialSupply to an address * @param _maxSupply max supply allowed * @param _initialSupply Optional amount to supply the first owner * @param _uri Optional URI for this token type * @param _data Optional data to pass if receiver is contract * @return tokenId The newly created token ID */ function create( uint256 _maxSupply, uint256 _initialSupply, string calldata _uri, bytes calldata _data ) external onlyWhitelistAdmin returns (uint256 tokenId) { require(_initialSupply <= _maxSupply, "Initial supply cannot be more than max supply"); uint256 _id = _getNextTokenID(); _incrementTokenTypeId(); creators[_id] = msg.sender; if (bytes(_uri).length > 0) { emit URI(_uri, _id); } if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data); tokenSupply[_id] = _initialSupply; tokenMaxSupply[_id] = _maxSupply; return _id; } /** * @dev Mints some amount of tokens to an address * @param _to Address of the future owner of the token * @param _id Token ID to mint * @param _quantity Amount of tokens to mint * @param _data Data to pass if receiver is contract */ function mint( address _to, uint256 _id, uint256 _quantity, bytes memory _data ) public onlyMinter { uint256 tokenId = _id; require(tokenSupply[tokenId].add(_quantity) <= tokenMaxSupply[tokenId], "Max supply reached"); _mint(_to, _id, _quantity, _data); tokenSupply[_id] = tokenSupply[_id].add(_quantity); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings. */ function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == _operator) { return true; } return ERC1155.isApprovedForAll(_owner, _operator); } /** * @dev Returns whether the specified token exists by checking to see if it has a creator * @param _id uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 _id) internal view returns (bool) { return creators[_id] != address(0); } /** * @dev calculates the next token ID based on value of _currentTokenID * @return uint256 for the next token ID */ function _getNextTokenID() private view returns (uint256) { return _currentTokenID.add(1); } /** * @dev increments the value of _currentTokenID */ function _incrementTokenTypeId() private { _currentTokenID++; } /** * @dev Updates token max supply * @param id_ uint256 ID of the token to update * @param maxSupply_ uint256 max supply allowed */ function updateTokenMaxSupply(uint256 id_, uint256 maxSupply_) external onlyWhitelistAdmin { require(_exists(id_), "ERC1155Tradable#updateTokenMaxSupply: NONEXISTENT_TOKEN"); require(tokenSupply[id_] <= maxSupply_, "already minted > new maxSupply"); tokenMaxSupply[id_] = maxSupply_; } } // SPDX-License-Identifier: MIT /** * @title EddaNft * EddaNft - Collect limited edition NFTs from Edda */ contract EddaNft is ERC1155Tradable { string public contractURI; constructor( string memory _name, //// "Meme Ltd." string memory _symbol, //// "MEMES" address _proxyRegistryAddress, string memory _baseMetadataURI, //// "https://api.dontbuymeme.com/memes/" string memory _contractURI //// "https://api.dontbuymeme.com/contract/memes-erc1155" ) public ERC1155Tradable(_name, _symbol, _proxyRegistryAddress) { contractURI = _contractURI; _setBaseMetadataURI(_baseMetadataURI); } //// function contractURI() public pure returns (string memory) { //// return "https://api.dontbuymeme.com/contract/memes-erc1155"; //// } }
Updates token max supply id_ uint256 ID of the token to update maxSupply_ uint256 max supply allowed/
function updateTokenMaxSupply(uint256 id_, uint256 maxSupply_) external onlyWhitelistAdmin { require(_exists(id_), "ERC1155Tradable#updateTokenMaxSupply: NONEXISTENT_TOKEN"); require(tokenSupply[id_] <= maxSupply_, "already minted > new maxSupply"); tokenMaxSupply[id_] = maxSupply_; }
11,639,296
pragma solidity ^0.4.25; import "browser/SafeMath.sol"; contract MiningShare { using SafeMath for uint256; address private owner = 0x0; uint256 private closeBlock = 0; mapping(address => uint256) private usersNTD; mapping(address => uint256) private usersWithdraw; uint256 private totalNTD = 0; uint256 private totalWithdraw = 0; modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyShareHolders() { require(usersNTD[msg.sender] != 0); _; } modifier beforeCloseBlock() { require(block.number <= closeBlock); _; } modifier afterCloseBlock() { require(block.number > closeBlock); _; } constructor() public { owner = msg.sender; closeBlock = block.number + 2000; } function CapitalIncrease(address account, uint256 NTD) public onlyOwner beforeCloseBlock { usersNTD[account] = usersNTD[account].add(NTD); totalNTD = totalNTD.add(NTD); } function CapitalDecrease(address account, uint256 NTD) public onlyOwner beforeCloseBlock { usersNTD[account] = usersNTD[account].sub(NTD); totalNTD = totalNTD.sub(NTD); } function MyTotalNTD() public constant onlyShareHolders returns (uint256) { return usersNTD[msg.sender]; } function MyTotalWithdraw() public constant onlyShareHolders afterCloseBlock returns (uint256) { return usersWithdraw[msg.sender]; } function TotalMined() public constant onlyShareHolders afterCloseBlock returns (uint256) { return totalWithdraw.add(address(this).balance); } function Withdraw() public onlyShareHolders afterCloseBlock { uint256 totalMined = totalWithdraw.add(address(this).balance); // totalMined * hisNTD / totalNTD - userWithdraw; uint256 userCanWithdraw = totalMined .mul(usersNTD[msg.sender].div(totalNTD)) .sub(usersWithdraw[msg.sender]); usersWithdraw[msg.sender].add(userCanWithdraw); totalWithdraw.add(userCanWithdraw); msg.sender.transfer(userCanWithdraw); } }
totalMined hisNTD / totalNTD - userWithdraw;
function Withdraw() public onlyShareHolders afterCloseBlock { uint256 totalMined = totalWithdraw.add(address(this).balance); uint256 userCanWithdraw = totalMined .mul(usersNTD[msg.sender].div(totalNTD)) .sub(usersWithdraw[msg.sender]); usersWithdraw[msg.sender].add(userCanWithdraw); totalWithdraw.add(userCanWithdraw); msg.sender.transfer(userCanWithdraw); }
12,996,344
// File: contracts/interfaces/IPriceModule.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; interface IPriceModule { function getUSDPrice(address ) external view returns(uint256); } // File: contracts/aps/APContract.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; // pragma experimental ABIEncoderV2; contract APContract { address public yieldsterDAO; address public yieldsterTreasury; address public yieldsterGOD; address public emergencyVault; address public yieldsterExchange; address public stringUtils; address public whitelistModule; address public whitelistManager; address public proxyFactory; address public priceModule; address public platFormManagementFee; address public profitManagementFee; address public stockDeposit; address public stockWithdraw; address public safeMinter; address public safeUtils; address public oneInch; struct Asset{ string name; string symbol; bool created; } struct Protocol{ string name; string symbol; bool created; } struct Vault { mapping(address => bool) vaultAssets; mapping(address => bool) vaultDepositAssets; mapping(address => bool) vaultWithdrawalAssets; mapping(address => bool) vaultEnabledStrategy; address depositStrategy; address withdrawStrategy; address vaultAPSManager; address vaultStrategyManager; uint256[] whitelistGroup; bool created; } struct VaultActiveStrategy { mapping(address => bool) isActiveStrategy; mapping(address => uint256) activeStrategyIndex; address[] activeStrategyList; } struct Strategy{ string strategyName; mapping(address => bool) strategyProtocols; bool created; address minter; address executor; address benefeciary; uint256 managementFeePercentage; } struct SmartStrategy{ string smartStrategyName; address minter; address executor; bool created; } struct vaultActiveManagemetFee { mapping(address => bool) isActiveManagementFee; mapping(address => uint256) activeManagementFeeIndex; address[] activeManagementFeeList; } event VaultCreation(address vaultAddress); mapping(address => vaultActiveManagemetFee) managementFeeStrategies; mapping(address => mapping(address => mapping(address => bool))) vaultStrategyEnabledProtocols; mapping(address => VaultActiveStrategy) vaultActiveStrategies; mapping(address => Asset) assets; mapping(address => Protocol) protocols; mapping(address => Vault) vaults; mapping(address => Strategy) strategies; mapping(address => SmartStrategy) smartStrategies; mapping(address => address) safeOwner; mapping(address => bool) APSManagers; mapping(address => address) minterStrategyMap; constructor( address _whitelistModule, address _platformManagementFee, address _profitManagementFee, address _stringUtils, address _yieldsterExchange, address _oneInch, address _priceModule, address _safeUtils ) public { yieldsterDAO = msg.sender; yieldsterTreasury = msg.sender; yieldsterGOD = msg.sender; emergencyVault = msg.sender; APSManagers[msg.sender] = true; whitelistModule = _whitelistModule; platFormManagementFee = _platformManagementFee; stringUtils = _stringUtils; yieldsterExchange = _yieldsterExchange; oneInch = _oneInch; priceModule = _priceModule; safeUtils = _safeUtils; profitManagementFee = _profitManagementFee; } /// @dev Function to add proxy Factory address to Yieldster. /// @param _proxyFactory Address of proxy factory. function addProxyFactory(address _proxyFactory) public onlyManager { proxyFactory = _proxyFactory; } function setProfitAndPlatformManagementFeeStrategies(address _platformManagement,address _profitManagement) public onlyYieldsterDAO { if (_profitManagement != address(0)) profitManagementFee = _profitManagement; if (_platformManagement != address(0)) platFormManagementFee = _platformManagement; } //Modifiers modifier onlyYieldsterDAO{ require(yieldsterDAO == msg.sender, "Only Yieldster DAO is allowed to perform this operation"); _; } modifier onlyManager{ require(APSManagers[msg.sender], "Only APS managers allowed to perform this operation!"); _; } modifier onlySafeOwner{ require(safeOwner[msg.sender] == tx.origin, "Only safe Owner can perform this operation"); _; } function isVault( address _address) public view returns(bool){ return vaults[_address].created; } /// @dev Function to add APS manager to Yieldster. /// @param _manager Address of the manager. function addManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = true; } /// @dev Function to remove APS manager from Yieldster. /// @param _manager Address of the manager. function removeManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = false; } /// @dev Function to change whitelist Manager. /// @param _whitelistManager Address of the whitelist manager. function changeWhitelistManager(address _whitelistManager) public onlyYieldsterDAO { whitelistManager = _whitelistManager; } /// @dev Function to set Yieldster GOD. /// @param _yieldsterGOD Address of the Yieldster GOD. function setYieldsterGOD(address _yieldsterGOD) public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = _yieldsterGOD; } /// @dev Function to disable Yieldster GOD. function disableYieldsterGOD() public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = address(0); } /// @dev Function to set Emergency vault. /// @param _emergencyVault Address of the Yieldster Emergency vault. function setEmergencyVault(address _emergencyVault) onlyYieldsterDAO public { emergencyVault = _emergencyVault; } /// @dev Function to set Safe Minter. /// @param _safeMinter Address of the Safe Minter. function setSafeMinter(address _safeMinter) onlyYieldsterDAO public { safeMinter = _safeMinter; } /// @dev Function to set safeUtils contract. /// @param _safeUtils Address of the safeUtils contract. function setSafeUtils(address _safeUtils) onlyYieldsterDAO public { safeUtils = _safeUtils; } /// @dev Function to set oneInch address. /// @param _oneInch Address of the oneInch. function setOneInch(address _oneInch) onlyYieldsterDAO public { oneInch = _oneInch; } /// @dev Function to get strategy address from minter. /// @param _minter Address of the minter. function getStrategyFromMinter(address _minter) external view returns(address) { return minterStrategyMap[_minter]; } /// @dev Function to set Yieldster Exchange. /// @param _yieldsterExchange Address of the Yieldster exchange. function setYieldsterExchange(address _yieldsterExchange) onlyYieldsterDAO public { yieldsterExchange = _yieldsterExchange; } /// @dev Function to set stock Deposit and Withdraw. /// @param _stockDeposit Address of the stock deposit contract. /// @param _stockWithdraw Address of the stock withdraw contract. function setStockDepositWithdraw(address _stockDeposit, address _stockWithdraw) onlyYieldsterDAO public { stockDeposit = _stockDeposit; stockWithdraw = _stockWithdraw; } /// @dev Function to change the APS Manager for a vault. /// @param _vaultAPSManager Address of the new APS Manager. function changeVaultAPSManager(address _vaultAPSManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultAPSManager = _vaultAPSManager; } /// @dev Function to change the Strategy Manager for a vault. /// @param _vaultStrategyManager Address of the new Strategy Manager. function changeVaultStrategyManager(address _vaultStrategyManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultStrategyManager = _vaultStrategyManager; } //Price Module /// @dev Function to set Yieldster price module. /// @param _priceModule Address of the price module. function setPriceModule(address _priceModule) public onlyManager { priceModule = _priceModule; } /// @dev Function to get the USD price for a token. /// @param _tokenAddress Address of the token. function getUSDPrice(address _tokenAddress) public view returns(uint256) { require(_isAssetPresent(_tokenAddress),"Asset not present!"); return IPriceModule(priceModule).getUSDPrice(_tokenAddress); } //Vaults /// @dev Function to create a vault. /// @param _owner Address of the owner of the vault. /// @param _vaultAddress Address of the new vault. function createVault(address _owner, address _vaultAddress) public { require(msg.sender == proxyFactory, "Only Proxy Factory can perform this operation"); safeOwner[_vaultAddress] = _owner; } /// @dev Function to add a vault in the APS. /// @param _vaultAPSManager Address of the vaults APS Manager. /// @param _vaultStrategyManager Address of the vaults Strateg Manager. /// @param _whitelistGroup List of whitelist groups applied to the vault. /// @param _owner Address of the vault owner. function addVault( address _vaultAPSManager, address _vaultStrategyManager, uint256[] memory _whitelistGroup, address _owner ) public { require(safeOwner[msg.sender] == _owner, "Only owner can call this function"); Vault memory newVault = Vault( { vaultAPSManager : _vaultAPSManager, vaultStrategyManager : _vaultStrategyManager, whitelistGroup : _whitelistGroup, depositStrategy: stockDeposit, withdrawStrategy: stockWithdraw, created : true }); vaults[msg.sender] = newVault; //applying Platform management fee managementFeeStrategies[msg.sender].isActiveManagementFee[platFormManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[platFormManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(platFormManagementFee); //applying Profit management fee managementFeeStrategies[msg.sender].isActiveManagementFee[profitManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[profitManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(profitManagementFee); } /// @dev Function to Manage the vault assets. /// @param _enabledDepositAsset List of deposit assets to be enabled in the vault. /// @param _enabledWithdrawalAsset List of withdrawal assets to be enabled in the vault. /// @param _disabledDepositAsset List of deposit assets to be disabled in the vault. /// @param _disabledWithdrawalAsset List of withdrawal assets to be disabled in the vault. function setVaultAssets( address[] memory _enabledDepositAsset, address[] memory _enabledWithdrawalAsset, address[] memory _disabledDepositAsset, address[] memory _disabledWithdrawalAsset ) public { require(vaults[msg.sender].created, "Vault not present"); for (uint256 i = 0; i < _enabledDepositAsset.length; i++) { address asset = _enabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; } for (uint256 i = 0; i < _enabledWithdrawalAsset.length; i++) { address asset = _enabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } for (uint256 i = 0; i < _disabledDepositAsset.length; i++) { address asset = _disabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; } for (uint256 i = 0; i < _disabledWithdrawalAsset.length; i++) { address asset = _disabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to get the list of management fee strategies applied to the vault. function getVaultManagementFee() public view returns(address[] memory) { require(vaults[msg.sender].created, "Vault not present"); return managementFeeStrategies[msg.sender].activeManagementFeeList; } /// @dev Function to get the deposit strategy applied to the vault. function getDepositStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].depositStrategy; } /// @dev Function to get the withdrawal strategy applied to the vault. function getWithdrawStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].withdrawStrategy; } /// @dev Function to set the management fee strategies applied to a vault. /// @param _vaultAddress Address of the vault. /// @param _managementFeeAddress Address of the management fee strategy. function setManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender, "Sender not Authorized"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = true; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress] = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length; managementFeeStrategies[_vaultAddress].activeManagementFeeList.push(_managementFeeAddress); } /// @dev Function to deactivate a vault strategy. /// @param _managementFeeAddress Address of the Management Fee Strategy. function removeManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress], "Provided ManagementFee is not active"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender || yieldsterDAO == msg.sender, "Sender not Authorized"); require(platFormManagementFee != _managementFeeAddress || yieldsterDAO == msg.sender,"Platfrom Management only changable by dao!"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = false; if(managementFeeStrategies[_vaultAddress].activeManagementFeeList.length == 1) { managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } else { uint256 index = managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress]; uint256 lastIndex = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length - 1; delete managementFeeStrategies[_vaultAddress].activeManagementFeeList[index]; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]] = index; managementFeeStrategies[_vaultAddress].activeManagementFeeList[index] = managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]; managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } } /// @dev Function to set vault active strategy. /// @param _strategyAddress Address of the strategy. function setVaultActiveStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = true; vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress] = vaultActiveStrategies[msg.sender].activeStrategyList.length; vaultActiveStrategies[msg.sender].activeStrategyList.push(_strategyAddress); } /// @dev Function to deactivate a vault strategy. /// @param _strategyAddress Address of the strategy. function deactivateVaultStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress], "Provided strategy is not active"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = false; if(vaultActiveStrategies[msg.sender].activeStrategyList.length == 1) { vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } else { uint256 index = vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress]; uint256 lastIndex = vaultActiveStrategies[msg.sender].activeStrategyList.length - 1; delete vaultActiveStrategies[msg.sender].activeStrategyList[index]; vaultActiveStrategies[msg.sender].activeStrategyIndex[vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]] = index; vaultActiveStrategies[msg.sender].activeStrategyList[index] = vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]; vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } } /// @dev Function to get vault active strategy. function getVaultActiveStrategy(address _vaultAddress) public view returns(address[] memory) { require(vaults[_vaultAddress].created, "Vault not present"); return vaultActiveStrategies[_vaultAddress].activeStrategyList; } function isStrategyActive(address _vaultAddress, address _strategyAddress) public view returns(bool) { return vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress]; } function getStrategyManagementDetails(address _vaultAddress, address _strategyAddress) public view returns(address, uint256) { require(vaults[_vaultAddress].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress], "Strategy not Active"); return (strategies[_strategyAddress].benefeciary, strategies[_strategyAddress].managementFeePercentage); } /// @dev Function to Manage the vault strategies. /// @param _vaultStrategy Address of the strategy. /// @param _enabledStrategyProtocols List of protocols that are enabled in the strategy. /// @param _disabledStrategyProtocols List of protocols that are disabled in the strategy. /// @param _assetsToBeEnabled List of assets that have to be enabled along with the strategy. function setVaultStrategyAndProtocol( address _vaultStrategy, address[] memory _enabledStrategyProtocols, address[] memory _disabledStrategyProtocols, address[] memory _assetsToBeEnabled ) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_vaultStrategy].created, "Strategy not present"); vaults[msg.sender].vaultEnabledStrategy[_vaultStrategy] = true; for (uint256 i = 0; i < _enabledStrategyProtocols.length; i++) { address protocol = _enabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = true; } for (uint256 i = 0; i < _disabledStrategyProtocols.length; i++) { address protocol = _disabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = false; } for (uint256 i = 0; i < _assetsToBeEnabled.length; i++) { address asset = _assetsToBeEnabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } } /// @dev Function to disable the vault strategies. /// @param _strategyAddress Address of the strategy. /// @param _assetsToBeDisabled List of assets that have to be disabled along with the strategy. function disableVaultStrategy(address _strategyAddress, address[] memory _assetsToBeDisabled) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaults[msg.sender].vaultEnabledStrategy[_strategyAddress], "Strategy was not enabled"); vaults[msg.sender].vaultEnabledStrategy[_strategyAddress] = false; for (uint256 i = 0; i < _assetsToBeDisabled.length; i++) { address asset = _assetsToBeDisabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to set smart strategy applied to the vault. /// @param _smartStrategyAddress Address of the smart strategy. /// @param _type type of smart strategy(deposit or withdraw). function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) public { require(vaults[msg.sender].created, "Vault not present"); require(_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not Supported by Yieldster"); if(_type == 1){ vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if(_type == 2){ vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else{ revert("Invalid type provided"); } } /// @dev Function to check if a particular protocol is enabled in a strategy for a vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. /// @param _protocolAddress Address of the protocol to check. function _isStrategyProtocolEnabled( address _vaultAddress, address _strategyAddress, address _protocolAddress ) public view returns(bool) { if( vaults[_vaultAddress].created && strategies[_strategyAddress].created && protocols[_protocolAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] && vaultStrategyEnabledProtocols[_vaultAddress][_strategyAddress][_protocolAddress]){ return true; } else{ return false; } } /// @dev Function to check if a strategy is enabled for the vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. function _isStrategyEnabled( address _vaultAddress, address _strategyAddress ) public view returns(bool) { if(vaults[_vaultAddress].created && strategies[_strategyAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress]){ return true; } else{ return false; } } /// @dev Function to check if the asset is supported by the vault. /// @param cleanUpAsset Address of the asset. function _isVaultAsset(address cleanUpAsset) public view returns(bool) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].vaultAssets[cleanUpAsset]; } // Assets /// @dev Function to check if an asset is supported by Yieldster. /// @param _address Address of the asset. function _isAssetPresent(address _address) private view returns(bool) { return assets[_address].created; } /// @dev Function to add an asset to the Yieldster. /// @param _symbol Symbol of the asset. /// @param _name Name of the asset. /// @param _tokenAddress Address of the asset. function addAsset( string memory _symbol, string memory _name, address _tokenAddress ) public onlyManager { require(!_isAssetPresent(_tokenAddress),"Asset already present!"); Asset memory newAsset = Asset({name:_name, symbol:_symbol, created:true}); assets[_tokenAddress] = newAsset; } /// @dev Function to remove an asset from the Yieldster. /// @param _tokenAddress Address of the asset. function removeAsset(address _tokenAddress) public onlyManager { require(_isAssetPresent(_tokenAddress),"Asset not present!"); delete assets[_tokenAddress]; } /// @dev Function to check if an asset is supported deposit asset in the vault. /// @param _assetAddress Address of the asset. function isDepositAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultDepositAssets[_assetAddress]; } /// @dev Function to check if an asset is supported withdrawal asset in the vault. /// @param _assetAddress Address of the asset. function isWithdrawalAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultWithdrawalAssets[_assetAddress]; } //Strategies /// @dev Function to check if a strategy is supported by Yieldster. /// @param _address Address of the strategy. function _isStrategyPresent(address _address) private view returns(bool) { return strategies[_address].created; } /// @dev Function to add a strategy to Yieldster. /// @param _strategyName Name of the strategy. /// @param _strategyAddress Address of the strategy. /// @param _strategyAddress List of protocols present in the strategy. /// @param _minter Address of strategy minter. /// @param _executor Address of strategy executor. function addStrategy( string memory _strategyName, address _strategyAddress, address[] memory _strategyProtocols, address _minter, address _executor, address _benefeciary, uint256 _managementFeePercentage ) public onlyManager { require(!_isStrategyPresent(_strategyAddress),"Strategy already present!"); Strategy memory newStrategy = Strategy({ strategyName:_strategyName, created:true, minter:_minter, executor:_executor, benefeciary:_benefeciary, managementFeePercentage: _managementFeePercentage}); strategies[_strategyAddress] = newStrategy; minterStrategyMap[_minter] = _strategyAddress; for (uint256 i = 0; i < _strategyProtocols.length; i++) { address protocol = _strategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); strategies[_strategyAddress].strategyProtocols[protocol] = true; } } /// @dev Function to remove a strategy from Yieldster. /// @param _strategyAddress Address of the strategy. function removeStrategy(address _strategyAddress) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); delete strategies[_strategyAddress]; } /// @dev Function to get strategy executor address. /// @param _strategy Address of the strategy. function strategyExecutor(address _strategy) external view returns(address) { return strategies[_strategy].executor; } /// @dev Function to change executor of strategy. /// @param _strategyAddress Address of the strategy. /// @param _executor Address of the executor. function changeStrategyExecutor(address _strategyAddress, address _executor) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); strategies[_strategyAddress].executor = _executor; } //Smart Strategy /// @dev Function to check if a smart strategy is supported by Yieldster. /// @param _address Address of the smart strategy. function _isSmartStrategyPresent(address _address) private view returns(bool) { return smartStrategies[_address].created; } /// @dev Function to add a smart strategy to Yieldster. /// @param _smartStrategyName Name of the smart strategy. /// @param _smartStrategyAddress Address of the smart strategy. function addSmartStrategy( string memory _smartStrategyName, address _smartStrategyAddress, address _minter, address _executor ) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy already present!"); SmartStrategy memory newSmartStrategy = SmartStrategy ({ smartStrategyName : _smartStrategyName, minter : _minter, executor : _executor, created : true }); smartStrategies[_smartStrategyAddress] = newSmartStrategy; minterStrategyMap[_minter] = _smartStrategyAddress; } /// @dev Function to remove a smart strategy from Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function removeSmartStrategy(address _smartStrategyAddress) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not present"); delete smartStrategies[_smartStrategyAddress]; } /// @dev Function to get ssmart strategy executor address. /// @param _smartStrategy Address of the strategy. function smartStrategyExecutor(address _smartStrategy) external view returns(address) { return smartStrategies[_smartStrategy].executor; } /// @dev Function to change executor of smart strategy. /// @param _smartStrategy Address of the smart strategy. /// @param _executor Address of the executor. function changeSmartStrategyExecutor(address _smartStrategy, address _executor) public onlyManager { require(_isSmartStrategyPresent(_smartStrategy),"Smart Strategy not present!"); smartStrategies[_smartStrategy].executor = _executor; } // Protocols /// @dev Function to check if a protocol is supported by Yieldster. /// @param _address Address of the protocol. function _isProtocolPresent(address _address) private view returns(bool) { return protocols[_address].created; } /// @dev Function to add a protocol to Yieldster. /// @param _symbol symbol of the protocol. /// @param _name Name of the protocol. /// @param _protocolAddress Address of the protocol. function addProtocol( string memory _symbol, string memory _name, address _protocolAddress ) public onlyManager { require(!_isProtocolPresent(_protocolAddress),"Protocol already present!"); Protocol memory newProtocol = Protocol({ name:_name, created:true, symbol:_symbol }); protocols[_protocolAddress] = newProtocol; } /// @dev Function to remove a protocol from Yieldster. /// @param _protocolAddress Address of the protocol. function removeProtocol(address _protocolAddress) public onlyManager { require(_isProtocolPresent(_protocolAddress),"Protocol not present!"); delete protocols[_protocolAddress]; } }
Function to set oneInch address. _oneInch Address of the oneInch.
function setOneInch(address _oneInch) onlyYieldsterDAO public { oneInch = _oneInch; }
5,938,188
pragma solidity ^0.5.2; /* * This file contains a set of contracts used to handle consents between a company * and a person. * * Copyright 2017 Tomas Stenlund, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /* * This is the contract that handles consent templates for a specific purpouse. It is used * when a person or entity wants to get a consent from another user. The consent is then * generated from this template. * * It basically provides a textual description of the consent. * */ contract ConsentTemplate { address private owner; /* The owner of the template */ address private creator; /* Creator of this template */ string private purpouse; /* What purpouse the template is for */ string private company; /* The name of the owner */ uint private version; /* Version of the purpouse, i.e. if the text or title changes for the same purpouse */ string private title; /* The title of the consent */ string private text; /* The text that describes the purpouse of the consent */ string private languageCountry; /* The language and country the consent template is valid for. * * Standard country-language code according to ISO 639 and ISO 3166-1 alpha 2 * separated by a dash, so for swedish in Sweden it is "sv-SE" */ /* Creates the contract and set the values of the contract. */ constructor (string memory _company, string memory _purpouse, uint _version, string memory _title, string memory _text, string memory _languageCountry) public { owner = tx.origin; creator = msg.sender; company = _company; purpouse = _purpouse; version = _version; title = _title; text = _text; languageCountry = _languageCountry; } /* Set of getters for the contract */ function getVersion () public view returns (uint) { return version; } function getTitle () public view returns (string memory) { return title; } function getPurpouse () public view returns (string memory) { return purpouse; } function getText () public view returns (string memory) { return text; } function getLanguageCountry () public view returns (string memory) { return languageCountry; } function getCompany() public view returns (string memory) { return company; } } /* * This is the contract that handles consents for a specific purpouse given by a * user (giver) to another user (owner). * * It basically provides a textual description that is either accepted or denied by a user. * */ contract Consent { /* Enumeration for the state of the consent */ enum Status {denied, /* The giver has denied the consent */ accepted, /* The giver has accepted the consent */ requested, /* The company has requested a consent, user has not yet responded */ cancelled /* The company has cancelled the consent because he no longer needs it */ } /* State variables for the contract */ address payable private owner; /* Who issues to consent form */ address private creator; /* Who created this object */ address private giver; /* Who gives the consent, address to the account. */ Status private status; /* The status of the consent */ address private consentTemplate; /* The template this consent is based on */ /* Event to signal that the status has changed */ event ConsentStatusChanged (address indexed consent, address indexed owner, address indexed giver, Status status); /* A modifier */ modifier onlyBy(address _account) { require(tx.origin == _account); _; } /* This function is executed at initialization and sets the owner and the giver of the consent */ /* as well as what it contains */ constructor (address _giver, address _consentTemplate) public { giver = _giver; owner = tx.origin; creator = msg.sender; consentTemplate = _consentTemplate; status = Status.requested; } /* Sets the status of the consent, this can only be done by the giver. */ function setStatus(Status _status) onlyBy (giver) public { if (_status == Status.denied || _status == Status.accepted) { status = _status; emit ConsentStatusChanged (address(this), owner, giver, _status); } } /* Cancels a consent, this can only be done by the company who created the consent. */ function cancel () onlyBy (owner) public { status = Status.cancelled; emit ConsentStatusChanged (address(this), owner, giver, Status.cancelled); } /* Returns the status of the consent */ function getStatus() public view returns (Status) { return status; } /* Returns the consent template that this consent is based on */ function getTemplate() public view returns (ConsentTemplate) { return ConsentTemplate(consentTemplate); } /* Returns with the giver */ function getGiver() public view returns (address) { return giver; } /* Returns with teh giver */ function getOwner() public view returns (address) { return owner; } /* Function to recover the funds on the contract */ function kill() public { if (tx.origin == owner) selfdestruct(owner); } } /* * This a list of consents that are offered to a specific account. * * This contains a list of consents that a specific user has been * offered. Regardless if it is deined, approved or has no decision. * */ contract ConsentFile { /* The owner of the file */ address private owner; address private creator; address private giver; /* The list of all consents */ address[] private listOfConsents; /* Events that are sent when things happen */ event ConsentFileConsentAdded (address indexed file, address indexed owner, address indexed giver, address consent); /* A modifier */ modifier onlyBy(address _account) { require(tx.origin == _account); _; } /* The constructor of the file. Also attaches it to an owner */ constructor (address _giver) public { owner = tx.origin; creator = msg.sender; giver = _giver; } /* Adds a new consent to the file */ function addConsent (address _consent) public { listOfConsents.push (_consent); emit ConsentFileConsentAdded (address(this), owner, giver, _consent); } /* Retrieve a list of all consents in the file */ function getListOfConsents () public view returns (address[] memory) { return listOfConsents; } /* Retrieves the owner */ function getGiver () public view returns (address) { return giver; } } /* * This is the consent factory contract that handles consents and version of * consents. * * It basically provides an interface to be able to create consents based on * a specific purpouse for a specific user. And always using the latest version * and always puts newly generated consents into a persons consent file. * */ contract ConsentFactory { /* Enumeration for errors */ enum Error {no_such_template, /* If no such template exists for the purpouse, language and country */ only_accepted_or_denied /* Tried to set wrong status on consent */ } /* The owner of this contract */ address payable private owner; /* Who owns this Consent Facotory, this is a company */ address private creator; /* Who created this factory */ string private company; /* Company that created this */ /* List of all templates in this factory */ address[] private listOfAllConsentTemplates; address[] private listOfActiveConsentTemplates; /* Contains a map from purpouse to language and country mapping to index into the list of active consent templates */ mapping (string => mapping (string => uint)) private consentTemplates; /* Events generated when the consent has been created */ event ConsentFactoryConsentCreatedEvent(address indexed factory, address indexed owner, address indexed user, address file, address consent); event ConsentFactoryFileCreatedEvent(address indexed factory, address indexed owner, address indexed user, address file); event ConsentFactoryFailedEvent(address indexed factory, address indexed owner, address indexed user, Error error); event ConsentFactoryTemplateAddedEvent (address indexed factory, address indexed owner, address template); event ConsentFactoryConsentStatusChangedEvent (address indexed factory, address indexed owner, address indexed user, Consent consent, Consent.Status status); /* A modifier */ modifier onlyBy(address _account) { require(tx.origin == _account); _; } /* Constructor for the consent factory */ constructor (string memory _company, address payable _owner) public { owner = _owner; creator = msg.sender; company = _company; } /* Adds a consent template to the factory to be used for consent generation. Should have a modifier for the company. */ function addConsentTemplate (string memory _purpouse, uint _version, string memory _title, string memory _text, string memory _languageCountry) public { /* Add the template for the specific language, country and purpouse */ uint ix = consentTemplates[_purpouse][_languageCountry]; address ct = address(new ConsentTemplate (company, _purpouse, _version, _title, _text, _languageCountry)); if (ix == 0) { ix = listOfActiveConsentTemplates.push (ct); consentTemplates[_purpouse][_languageCountry] = ix; } else { listOfActiveConsentTemplates[ix-1] = ct; } listOfAllConsentTemplates.push(ct); emit ConsentFactoryTemplateAddedEvent (address(this), owner, ct); } /* Returns with a list of active consent templates */ function getActiveConsentTemplates() onlyBy (owner) public view returns (address[] memory) { return listOfActiveConsentTemplates; } /* Returns with a list of all consent templates */ function getAllConsentTemplates() onlyBy (owner) public view returns (address[] memory) { return listOfAllConsentTemplates; } /* Create a file that holds a users all consents. * * This is the file that holds all consents regardless of their state. Should have a modifier for the company. */ function createConsentFile (address _user) onlyBy (owner) public { address file = address(new ConsentFile (_user)); emit ConsentFactoryFileCreatedEvent(address(this), owner, _user, file); } /* Create a consent for a specific purpouse of the latest version, language and country. * * Country and Purpouse must exist otherwise it will fail, if language is not there it will * default to countrys default language if it exists otherwise it will fail. It adds * the consent to the users file as well. Should have a modifier for the company only. */ function createConsent (address _file, string memory _purpouse, string memory _languageCountry) onlyBy (owner) public { ConsentFile cf = ConsentFile (_file); ConsentTemplate ct = getTemplate (_purpouse, _languageCountry); if (address(ct) != address(0)) { /* We got a template so generate the consent and put it into the consent file */ Consent consent = new Consent (cf.getGiver(), address(ct)); ConsentFile(_file).addConsent (address(consent)); emit ConsentFactoryConsentCreatedEvent(address(this), owner, cf.getGiver(), _file, address(consent)); } else { emit ConsentFactoryFailedEvent(address(this), owner, cf.getGiver(), Error.no_such_template); } } /* This function tests wether a consent for a specific purpouse exists or not */ function getTemplate (string memory _purpouse, string memory _languageCountry) view internal returns (ConsentTemplate) { /* Get the consents for a specific purpouse and language, country*/ uint ix = consentTemplates[_purpouse][_languageCountry]; if (ix == 0) { /* Fallback here is to only go for the default language of the country */ /* So we need to strip the language from the country */ bytes memory b = bytes (_languageCountry); if (b.length==5) { if (uint8(b[2]) == 45) { bytes memory c = new bytes(2); /* Get the country */ c[0] = b[3]; c[1] = b[4]; ix = consentTemplates[_purpouse][string(c)]; } } } /* Return the consent template if we found any */ if (ix>0) return ConsentTemplate(listOfActiveConsentTemplates[ix-1]); else return ConsentTemplate(address(0)); } /* Change the status of the consent */ function setConsentStatus(Consent _consent, Consent.Status _status) onlyBy (_consent.getGiver()) public { if(_status == Consent.Status.accepted || _status == Consent.Status.denied) { _consent.setStatus (_status); emit ConsentFactoryConsentStatusChangedEvent (address(this), _consent.getOwner(), _consent.getGiver(), _consent, _status); } else { emit ConsentFactoryFailedEvent (address(this), _consent.getOwner(), _consent.getGiver(), Error.only_accepted_or_denied); } } /* Cancel the consent */ function cancelConsent(Consent _consent) onlyBy (_consent.getOwner()) public { _consent.cancel(); emit ConsentFactoryConsentStatusChangedEvent (address(this), _consent.getOwner(), _consent.getGiver(), _consent, Consent.Status.cancelled); } /* The company who has this factory */ function getCompany() public view returns (string memory) { return company; } /* Returns the owner for the factory */ function getOwner() public view returns (address) { return owner; } /* Function to recover the funds on the contract */ function kill() public { if (msg.sender == owner) selfdestruct(owner); } } /* * END */
Cancels a consent, this can only be done by the company who created the consent. /
function cancel () onlyBy (owner) public { status = Status.cancelled; emit ConsentStatusChanged (address(this), owner, giver, Status.cancelled); }
6,431,271
pragma solidity ^0.6.0; // SPDX-License-Identifier: UNLICENSED /** * @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; } function ceil(uint256 a, uint256 m) internal pure returns (uint256 r) { require(m != 0, "SafeMath: to ceil number shall not be zero"); return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- /** * @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); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // 'VANILLA' token AND staking contract // Symbol : VNLA // Name : Vanilla Network // Total supply: 1,000,000 (1 million) // Min supply : 100k // Decimals : 18 // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Vanilla is IERC20, Owned { using SafeMath for uint256; string public symbol = "VNLA"; string public name = "Vanilla Network"; uint256 public decimals = 18; address airdropContract; uint256 _totalSupply = 98447685 * 10 ** (16); // 984,476.85 mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(address icoContract, address _airdropContract) public { airdropContract = _airdropContract; owner = 0xFa50b82cbf2942008A097B6289F39b1bb797C5Cd; balances[icoContract] = 150000 * 10 ** (18); // 150,000 emit Transfer(address(0), icoContract, 150000 * 10 ** (18)); balances[address(owner)] = 54195664 * 10 ** (16); // 541,956.64 emit Transfer(address(0), address(owner), 54195664 * 10 ** (16)); balances[address(airdropContract)] = 2925202086 * 10 ** (14); // 292520.2086 emit Transfer(address(0), address(airdropContract), 2925202086 * 10 ** (14)); } /** ERC20Interface function's implementation **/ function totalSupply() external override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) external override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // ------------------------------------------------------------------------ function approve(address spender, uint256 tokens) external override returns (bool success){ allowed[msg.sender][spender] = tokens; emit Approval(msg.sender,spender,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) external override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); uint256 deduction = deductionsToApply(tokens); applyDeductions(deduction); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(msg.sender, to, tokens.sub(deduction)); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) external override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); uint256 deduction = deductionsToApply(tokens); applyDeductions(deduction); balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(from, to, tokens.sub(tokens)); return true; } function _transfer(address to, uint256 tokens, bool rewards) internal returns(bool){ // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[address(this)] >= tokens ); require(balances[to] + tokens >= balances[to]); balances[address(this)] = balances[address(this)].sub(tokens); uint256 deduction = 0; if(!rewards){ deduction = deductionsToApply(tokens); applyDeductions(deduction); } balances[to] = balances[to].add(tokens.sub(deduction)); emit Transfer(address(this),to,tokens.sub(deduction)); return true; } function deductionsToApply(uint256 tokens) private view returns(uint256){ uint256 deduction = 0; uint256 minSupply = 100000 * 10 ** (18); if(_totalSupply > minSupply && msg.sender != airdropContract){ deduction = onePercent(tokens).mul(5); // 5% transaction cost if(_totalSupply.sub(deduction) < minSupply) deduction = _totalSupply.sub(minSupply); } return deduction; } function applyDeductions(uint256 deduction) private{ if(stakedCoins == 0){ burnTokens(deduction); } else{ burnTokens(deduction.div(2)); disburse(deduction.div(2)); } } // ------------------------------------------------------------------------ // Burn the ``value` amount of tokens from the `account` // ------------------------------------------------------------------------ function burnTokens(uint256 value) internal{ require(_totalSupply >= value); // burn only unsold tokens _totalSupply = _totalSupply.sub(value); emit Transfer(msg.sender, address(0), value); } // ------------------------------------------------------------------------ // Calculates onePercent of the uint256 amount sent // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) internal pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } /********************************STAKING CONTRACT**********************************/ uint256 deployTime; uint256 private totalDividentPoints; uint256 private unclaimedDividendPoints; uint256 pointMultiplier = 1000000000000000000; uint256 public stakedCoins; uint256 public totalRewardsClaimed; bool public stakingOpen; struct Account { uint256 balance; uint256 lastDividentPoints; uint256 timeInvest; uint256 lastClaimed; uint256 rewardsClaimed; uint256 pending; } mapping(address => Account) accounts; function openStaking() external onlyOwner{ require(!stakingOpen, "staking already open"); stakingOpen = true; } function STAKE(uint256 _tokens) external returns(bool){ require(stakingOpen, "staking is close"); // gets VANILLA tokens from user to contract address require(transfer(address(this), _tokens), "In sufficient tokens in user wallet"); // require(_tokens >= 100 * 10 ** (18), "Minimum stake allowed is 100 EZG"); uint256 owing = dividendsOwing(msg.sender); if(owing > 0) // early stakes accounts[msg.sender].pending = owing; addToStake(_tokens); return true; } function addToStake(uint256 _tokens) private{ uint256 deduction = deductionsToApply(_tokens); if(accounts[msg.sender].balance == 0 ) // first time staking accounts[msg.sender].timeInvest = now; stakedCoins = stakedCoins.add(_tokens.sub(deduction)); accounts[msg.sender].balance = accounts[msg.sender].balance.add(_tokens.sub(deduction)); accounts[msg.sender].lastDividentPoints = totalDividentPoints; accounts[msg.sender].lastClaimed = now; } function stakingStartedAt(address user) external view returns(uint256){ return accounts[user].timeInvest; } function pendingReward(address _user) external view returns(uint256){ uint256 owing = dividendsOwing(_user); return owing; } function dividendsOwing(address investor) internal view returns (uint256){ uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints); return (((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier)).add(accounts[investor].pending); } function updateDividend(address investor) internal returns(uint256){ uint256 owing = dividendsOwing(investor); if (owing > 0){ unclaimedDividendPoints = unclaimedDividendPoints.sub(owing); accounts[investor].lastDividentPoints = totalDividentPoints; accounts[investor].pending = 0; } return owing; } function activeStake(address _user) external view returns (uint256){ return accounts[_user].balance; } function UNSTAKE(uint256 tokens) external returns (bool){ require(accounts[msg.sender].balance > 0); uint256 owing = updateDividend(msg.sender); if(owing > 0) // unclaimed reward accounts[msg.sender].pending = owing; stakedCoins = stakedCoins.sub(tokens); require(_transfer(msg.sender, tokens, false)); accounts[msg.sender].balance = accounts[msg.sender].balance.sub(tokens); return true; } function disburse(uint256 amount) internal{ balances[address(this)] = balances[address(this)].add(amount); uint256 unnormalized = amount.mul(pointMultiplier); totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins)); unclaimedDividendPoints = unclaimedDividendPoints.add(amount); } function claimReward() external returns(bool){ uint256 owing = updateDividend(msg.sender); require(owing > 0); require(_transfer(msg.sender, owing, true)); accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing); totalRewardsClaimed = totalRewardsClaimed.add(owing); return true; } function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){ return accounts[_user].rewardsClaimed; } function reinvest() external { uint256 owing = updateDividend(msg.sender); require(owing > 0); // if there is any pending reward, people can add it to existing stake addToStake(owing); } }
------------------------------------------------------------------------ Returns the amount of tokens approved by the owner that can be transferred to the spender's account ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) external override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; }
617,560
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; //import {SafeMathUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; import {IERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol'; import {IERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import {SafeERC20Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol'; import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol'; import {Decimal} from './Decimal.sol'; import {ZapMedia} from './ZapMedia.sol'; import {IMarket} from './interfaces/IMarket.sol'; import {Ownable} from './access/Ownable.sol'; /** * @title A Market for pieces of media * @notice This contract contains all of the market logic for Media */ contract ZapMarket is IMarket, Ownable { using SafeERC20Upgradeable for IERC20Upgradeable; /* ******* * Globals * ******* */ // Address of the media contract that can call this market mapping(address => address[]) public mediaContracts; // Mapping from media address to a bool showing whether or not // they're registered by the media factory mapping(address => bool) public registeredMedias; // registered media factory address address mediaFactory; // Mapping from token to mapping from bidder to bid mapping(address => mapping(uint256 => mapping(address => Bid))) private _tokenBidders; // Mapping from token to the bid shares for the token mapping(address => mapping(uint256 => BidShares)) private _bidShares; // Mapping from token to the current ask for the token mapping(address => mapping(uint256 => Ask)) private _tokenAsks; // Mapping from Media address to the Market configuration status mapping(address => bool) public isConfigured; // Mapping of token ids of accepted bids to their mutex mapping(uint256 => bool) private bidMutex; address platformAddress; IMarket.PlatformFee platformFee; /* ********* * Modifiers * ********* */ /** * @notice require that the msg.sender is the configured media contract */ modifier onlyMediaCaller() { require( isConfigured[msg.sender] == true, 'Market: Only media contract' ); _; } modifier onlyMediaFactory() { require( msg.sender == mediaFactory, 'Market: Only the media factory can do this action' ); _; } modifier isUnlocked(uint256 tokenId) { require(!bidMutex[tokenId], 'There is a bid transaction in progress'); bidMutex[tokenId] = true; _; bidMutex[tokenId] = false; } /* **************** * View Functions * **************** */ function bidForTokenBidder( address mediaContractAddress, uint256 tokenId, address bidder ) external view override returns (Bid memory) { return _tokenBidders[mediaContractAddress][tokenId][bidder]; } function currentAskForToken(address mediaContractAddress, uint256 tokenId) external view override returns (Ask memory) { return _tokenAsks[mediaContractAddress][tokenId]; } function bidSharesForToken(address mediaContractAddress, uint256 tokenId) public view override returns (BidShares memory) { return _bidShares[mediaContractAddress][tokenId]; } /** * @notice Validates that the bid is valid by ensuring that the bid amount can be split perfectly into all the bid shares. * We do this by comparing the sum of the individual share values with the amount and ensuring they are equal. Because * the splitShare function uses integer division, any inconsistencies with the original and split sums would be due to * a bid splitting that does not perfectly divide the bid amount. */ function isValidBid( address mediaContractAddress, uint256 tokenId, uint256 bidAmount ) public view override returns (bool) { BidShares memory bidShares = bidSharesForToken( mediaContractAddress, tokenId ); require( isValidBidShares(bidShares), 'Market: Invalid bid shares for token' ); uint256 collabShareValue = 0; Decimal.D256 memory thisCollabsShare; thisCollabsShare.value = 0; for (uint256 i = 0; i < bidShares.collaborators.length; i++) { thisCollabsShare.value = bidShares.collabShares[i]; collabShareValue = collabShareValue + (splitShare(thisCollabsShare, bidAmount)); } return bidAmount != 0 && (bidAmount == splitShare(bidShares.creator, bidAmount) + (collabShareValue) + (splitShare(platformFee.fee, bidAmount)) + (splitShare(bidShares.owner, bidAmount))); } /** * @notice Validates that the provided bid shares sum to 100 */ function isValidBidShares(BidShares memory bidShares) public view override returns (bool) { uint256 collabSharePerc = 0; for (uint256 i = 0; i < bidShares.collaborators.length; i++) { collabSharePerc = collabSharePerc + (bidShares.collabShares[i]); } return bidShares.creator.value + (collabSharePerc) + (bidShares.owner.value) + (platformFee.fee.value) == uint256(100) * (Decimal.BASE); } /** * @notice return a % of the specified amount. This function is used to split a bid into shares * for a media's shareholders. */ function splitShare(Decimal.D256 memory sharePercentage, uint256 amount) public pure override returns (uint256) { return Decimal.mul(amount, sharePercentage) / (100); } /* **************** * Public Functions * **************** */ function initializeMarket(address _platformAddress) public initializer { owner = msg.sender; platformAddress = _platformAddress; } function isRegistered(address mediaContractAddress) public view override returns (bool) { return (registeredMedias[mediaContractAddress]); } function setMediaFactory(address _mediaFactory) external override onlyOwner { mediaFactory = _mediaFactory; } function viewFee() public view returns (Decimal.D256 memory) { return platformFee.fee; } function setFee(IMarket.PlatformFee memory newFee) public onlyOwner { platformFee = newFee; } /** * @notice Sets the media contract address. This address is the only permitted address that * can call the mutable functions. This method can only be called once. */ function configure( address deployer, address mediaContract, bytes32 name, bytes32 symbol ) external override onlyMediaFactory { require( isConfigured[mediaContract] != true, 'Market: Already configured' ); require( mediaContract != address(0) && deployer != address(0), 'Market: cannot set media contract as zero address' ); isConfigured[mediaContract] = true; mediaContracts[deployer].push(mediaContract); emit MediaContractCreated(mediaContract, name, symbol); } function mintOrBurn( bool isMint, uint256 tokenId, address mediaContract ) external override { require(msg.sender == mediaContract, 'Market: Media only function'); if (isMint == true) { emit Minted(tokenId, mediaContract); } else { emit Burned(tokenId, mediaContract); } } function registerMedia(address mediaContract) external override onlyMediaFactory { registeredMedias[mediaContract] = true; } function revokeRegistration(address mediaContract) external override onlyOwner { registeredMedias[mediaContract] = false; } /** * @notice Sets bid shares for a particular tokenId. These bid shares must * sum to 100. */ function setBidShares(uint256 tokenId, BidShares memory bidShares) public override onlyMediaCaller { require( isValidBidShares(bidShares), 'Market: Invalid bid shares, must sum to 100' ); _bidShares[msg.sender][tokenId] = bidShares; emit BidShareUpdated(tokenId, bidShares, msg.sender); } /** * @notice Sets the ask on a particular media. If the ask cannot be evenly split into the media's * bid shares, this reverts. */ function setAsk(uint256 tokenId, Ask memory ask) public override onlyMediaCaller { require( isValidBid(msg.sender, tokenId, ask.amount), 'Market: Ask invalid for share splitting' ); _tokenAsks[msg.sender][tokenId] = ask; emit AskCreated(msg.sender, tokenId, ask); } /** * @notice removes an ask for a token and emits an AskRemoved event */ function removeAsk(uint256 tokenId) external override onlyMediaCaller { emit AskRemoved(tokenId, _tokenAsks[msg.sender][tokenId], msg.sender); delete _tokenAsks[msg.sender][tokenId]; } /** * @notice Sets the bid on a particular media for a bidder. The token being used to bid * is transferred from the spender to this contract to be held until removed or accepted. * If another bid already exists for the bidder, it is refunded. */ function setBid( uint256 tokenId, Bid memory bid, address spender ) public override onlyMediaCaller { BidShares memory bidShares = _bidShares[msg.sender][tokenId]; require( bidShares.creator.value + (bid.sellOnShare.value) <= uint256(100) * (Decimal.BASE), 'Market: Sell on fee invalid for share splitting' ); require(bid.bidder != address(0), 'Market: bidder cannot be 0 address'); require(bid.amount != 0, 'Market: cannot bid amount of 0'); require( bid.currency != address(0), 'Market: bid currency cannot be 0 address' ); require( bid.recipient != address(0), 'Market: bid recipient cannot be 0 address' ); Bid storage existingBid = _tokenBidders[msg.sender][tokenId][ bid.bidder ]; // If there is an existing bid, refund it before continuing if (existingBid.amount > 0) { removeBid(tokenId, bid.bidder); } IERC20Upgradeable token = IERC20Upgradeable(bid.currency); // We must check the balance that was actually transferred to the market, // as some tokens impose a transfer fee and would not actually transfer the // full amount to the market, resulting in locked funds for refunds & bid acceptance uint256 beforeBalance = token.balanceOf(address(this)); token.safeTransferFrom(spender, address(this), bid.amount); require( token.balanceOf(address(this)) == beforeBalance + bid.amount, 'Market: Market balance did not increase from bid' ); _tokenBidders[msg.sender][tokenId][bid.bidder] = Bid( bid.amount, bid.currency, bid.bidder, bid.recipient, bid.sellOnShare ); emit BidCreated(msg.sender, tokenId, bid); // If a bid meets the criteria for an ask, automatically accept the bid. // If no ask is set or the bid does not meet the requirements, ignore. if ( _tokenAsks[msg.sender][tokenId].currency != address(0) && bid.currency == _tokenAsks[msg.sender][tokenId].currency && bid.amount >= _tokenAsks[msg.sender][tokenId].amount ) { // Finalize exchange _finalizeNFTTransfer(msg.sender, tokenId, bid.bidder); } } /** * @notice Removes the bid on a particular media for a bidder. The bid amount * is transferred from this contract to the bidder, if they have a bid placed. */ function removeBid(uint256 tokenId, address bidder) public override onlyMediaCaller isUnlocked(tokenId) { Bid storage bid = _tokenBidders[msg.sender][tokenId][bidder]; uint256 bidAmount = bid.amount; address bidCurrency = bid.currency; require(bid.amount > 0, 'Market: cannot remove bid amount of 0'); IERC20Upgradeable token = IERC20Upgradeable(bidCurrency); emit BidRemoved(tokenId, bid, msg.sender); delete _tokenBidders[msg.sender][tokenId][bidder]; token.safeTransfer(bidder, bidAmount); } /** * @notice Accepts a bid from a particular bidder. Can only be called by the media contract. * See {_finalizeNFTTransfer} * Provided bid must match a bid in storage. This is to prevent a race condition * where a bid may change while the acceptBid call is in transit. * A bid cannot be accepted if it cannot be split equally into its shareholders. * This should only revert in rare instances (example, a low bid with a zero-decimal token), * but is necessary to ensure fairness to all shareholders. */ function acceptBid( address mediaContractAddress, uint256 tokenId, Bid calldata expectedBid ) external override onlyMediaCaller isUnlocked(tokenId) { Bid memory bid = _tokenBidders[mediaContractAddress][tokenId][ expectedBid.bidder ]; require(bid.amount > 0, 'Market: cannot accept bid of 0'); require( bid.amount == expectedBid.amount && bid.currency == expectedBid.currency && bid.sellOnShare.value == expectedBid.sellOnShare.value && bid.recipient == expectedBid.recipient, 'Market: Unexpected bid found.' ); require( isValidBid(mediaContractAddress, tokenId, bid.amount), 'Market: Bid invalid for share splitting' ); _finalizeNFTTransfer(mediaContractAddress, tokenId, bid.bidder); } /** * @notice Given a token ID and a bidder, this method transfers the value of * the bid to the shareholders. It also transfers the ownership of the media * to the bid recipient. Finally, it removes the accepted bid and the current ask. */ function _finalizeNFTTransfer( address mediaContractAddress, uint256 tokenId, address bidder ) private { Bid memory bid = _tokenBidders[mediaContractAddress][tokenId][bidder]; BidShares storage bidShares = _bidShares[mediaContractAddress][tokenId]; IERC20Upgradeable token = IERC20Upgradeable(bid.currency); // Transfer bid share to owner of media token.safeTransfer( IERC721Upgradeable(mediaContractAddress).ownerOf(tokenId), splitShare(bidShares.owner, bid.amount) ); // Transfer bid share to creator of media token.safeTransfer( ZapMedia(mediaContractAddress).getTokenCreators(tokenId), splitShare(bidShares.creator, bid.amount) ); uint256 collaboratorShares = 0; Decimal.D256 memory thisCollabsShare; thisCollabsShare.value = 0; // Transfer bid share to the remaining media collaborators for (uint256 i = 0; i < bidShares.collaborators.length; i++) { collaboratorShares = collaboratorShares + (bidShares.collabShares[i]); thisCollabsShare.value = bidShares.collabShares[i]; token.safeTransfer( bidShares.collaborators[i], splitShare(thisCollabsShare, bid.amount) ); } // Transfer bid share to previous owner of media (if applicable) token.safeTransfer( // ZapMedia(mediaContractAddress).getPreviousTokenOwners(tokenId), platformAddress, splitShare(platformFee.fee, bid.amount) ); // Transfer media to bid recipient ZapMedia(mediaContractAddress).auctionTransfer(tokenId, bid.recipient); // Calculate the bid share for the new owner, // equal to 100 - creatorShare - sellOnShare bidShares.owner = Decimal.D256( uint256(100) * (Decimal.BASE) - (collaboratorShares) - (_bidShares[mediaContractAddress][tokenId].creator.value) - (platformFee.fee.value) ); // Set the previous owner share to the accepted bid's sell-on fee // platformFee.fee = bid.sellOnShare; // Remove the accepted bid delete _tokenBidders[mediaContractAddress][tokenId][bidder]; emit BidShareUpdated(tokenId, bidShares, mediaContractAddress); emit BidFinalized(tokenId, bid, mediaContractAddress); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT 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"; import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable 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( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable 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( IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } } } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo * at commit 2d8454e02702fe5bc455b848556660629c3cad36 * * It has two modifications: * - it uses a newer solidity in the pragma to match the rest of the contract suite of this project * - it uses BASE_POW to add a level of abstraction for BASE */ import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {Math} from './Math.sol'; /** * @title Decimal * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE_POW = 18; uint256 constant BASE = 10**BASE_POW; // ============ Structs ============ struct D256 { uint256 value; } // ============ Functions ============ function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function onePlus(D256 memory d) internal pure returns (D256 memory) { return D256({value: d.value.add(BASE)}); } function mul(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, d.value, BASE); } function div(uint256 target, D256 memory d) internal pure returns (uint256) { return Math.getPartial(target, BASE, d.value); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/utils/introspection/ERC165StorageUpgradeable.sol'; // exposes _registerInterface import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import {SafeMath} from '@openzeppelin/contracts/utils/math/SafeMath.sol'; import {Math} from '@openzeppelin/contracts/utils/math/Math.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {Counters} from '@openzeppelin/contracts/utils/Counters.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; import {IMarket} from './interfaces/IMarket.sol'; import {IMedia} from './interfaces/IMedia.sol'; import {Ownable} from './Ownable.sol'; import {MediaGetter} from './MediaGetter.sol'; import {MediaStorage} from './libraries/MediaStorage.sol'; import './libraries/Constants.sol'; /** * @title A media value system, with perpetual equity to creators * @notice This contract provides an interface to mint media with a market * owned by the creator. */ contract ZapMedia is IMedia, ERC721BurnableUpgradeable, ReentrancyGuardUpgradeable, Ownable, MediaGetter, ERC721URIStorageUpgradeable, ERC721EnumerableUpgradeable, ERC165StorageUpgradeable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; using SafeMath for uint256; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * DEBUG(need to find the remaining methods that result to the new interfaceId ) * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ mapping(bytes4 => bool) private _supportedInterfaces; bytes internal _contractURI; bytes32 private constant kecEIP712Domain = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 private constant kecOne = keccak256(bytes('1')); bytes32 private kecName; /* ********* * Modifiers * ********* */ /** * @notice Require that the token has not been burned and has been minted */ modifier onlyExistingToken(uint256 tokenId) { require( _exists(tokenId), // remove revert string before deployment to mainnet 'Media: nonexistent token' ); _; } /** * @notice Require that the token has had a content hash set */ modifier onlyTokenWithContentHash(uint256 tokenId) { require( getTokenContentHashes(tokenId) != 0, // remove revert string before deployment to mainnet 'Media: token does not have hash of created content' ); _; } /** * @notice Require that the token has had a metadata hash set */ modifier onlyTokenWithMetadataHash(uint256 tokenId) { require( tokens.tokenMetadataHashes[tokenId] != 0, // remove revert string before deployment to mainnet 'Media: token does not have hash of its metadata' ); _; } /** * @notice Ensure that the provided spender is the approved or the owner of * the media for the specified tokenId */ modifier onlyApprovedOrOwner(address spender, uint256 tokenId) { require( _isApprovedOrOwner(spender, tokenId), // remove revert string before deployment to mainnet 'Media: Only approved or owner' ); _; } /** * @notice Ensure the token has been created (even if it has been burned) */ modifier onlyTokenCreated(uint256 tokenId) { require( access._tokenIdTracker.current() > tokenId, // remove revert string before deployment to mainnet 'Media: token with that id does not exist' ); _; } /** * @notice Ensure that the provided URI is not empty */ modifier onlyValidURI(string memory uri) { require( bytes(uri).length != 0, // remove revert string before deployment to mainnet 'Media: specified uri must be non-empty' ); _; } //geting the contractURI value function contractURI() public view returns (bytes memory) { return _contractURI; } /** * @notice On deployment, set the market contract address and register the * ERC721 metadata interface */ function initialize( string calldata name, string calldata symbol, address marketContractAddr, bool permissive, string calldata collectionURI ) external override initializer { __ERC721_init(name, symbol); initialize_ownable(); access.marketContract = marketContractAddr; bytes memory name_b = bytes(name); bytes32 name_b32; assembly { name_b32 := mload(add(name_b, 32)) } kecName = keccak256(name_b); _registerInterface(0x80ac58cd); // registers old erc721 interface for AucitonHouse _registerInterface(0x5b5e139f); // registers current metadata upgradeable interface for AuctionHouse _registerInterface(type(IMedia).interfaceId); access.isPermissive = permissive; _contractURI = bytes(collectionURI); } /** * @notice Returns a boolean, showing whether or not the given interfaceId is supported * @dev This function is overriden from the ERC721 and ERC165 contract stack * @param interfaceId a bytes4 formatted representation of a contract interface * @return boolean dipicting whether or not the interface is supported */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC721EnumerableUpgradeable, ERC721Upgradeable, ERC165StorageUpgradeable ) returns (bool) { return super.supportsInterface(interfaceId); } /** * @notice return the URI for a particular piece of media with the specified tokenId * @dev This function is an override of the base OZ implementation because we * will return the tokenURI even if the media has been burned. In addition, this * protocol does not support a base URI, so relevant conditionals are removed. * @return the URI for a token */ function tokenURI(uint256 tokenId) public view virtual override(ERC721URIStorageUpgradeable, ERC721Upgradeable) onlyTokenCreated(tokenId) returns (string memory) { return ERC721URIStorageUpgradeable.tokenURI(tokenId); } function _registerInterface(bytes4 interfaceId) internal virtual override { require(interfaceId != 0xffffffff, 'ERC165: invalid interface id'); _supportedInterfaces[interfaceId] = true; } /// @notice TokenTransfer hook function /// @dev called from ERC721 Enumerable Upgradeable contract, see here https://docs.openzeppelin.com/contracts/4.x/api/token/erc721#ERC721Enumerable-_beforeTokenTransfer-address-address-uint256- /// @param from the current token owner, if this is the zero address, the token will be minted for `to` /// @param to the receiver's wallet address, if this is the zero address, the token will be burned /// @param tokenId token ID of the ERC721 to be transfered function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721EnumerableUpgradeable, ERC721Upgradeable) { ERC721EnumerableUpgradeable._beforeTokenTransfer(from, to, tokenId); } /* ************* * View Functions * ************** */ /** * @notice Return the metadata URI for a piece of media given the token URI * @param tokenId the token whose metadata will be attached * @return the metadata URI for the token */ function tokenMetadataURI(uint256 tokenId) external view override onlyTokenCreated(tokenId) returns (string memory) { return access._tokenMetadataURIs[tokenId]; } /* **************** * Public Functions * **************** */ /** * @notice see IMedia * @dev mints an NFT and sets the bidshares for collaborators * @param data The media's metadata and content data, includes content and metadata hash, and token's URI */ function mint(MediaData memory data, IMarket.BidShares memory bidShares) public override nonReentrant { require( access.isPermissive || access.approvedToMint[msg.sender] || access.owner == msg.sender, 'Media: Only Approved users can mint' ); require( bidShares.collaborators.length == bidShares.collabShares.length, 'Media: Arrays do not have the same length' ); for (uint256 i = 0; i < bidShares.collaborators.length; i++) { require( _hasShares(i, bidShares), 'Media: Each collaborator must have a share of the nft' ); } _mintForCreator(msg.sender, data, bidShares); } /** * @notice see IMedia */ function mintWithSig( address creator, MediaData memory data, IMarket.BidShares memory bidShares, EIP712Signature memory sig ) public override nonReentrant { require( access.isPermissive || access.approvedToMint[msg.sender], 'Media: Only Approved users can mint' ); require( sig.deadline == 0 || sig.deadline >= block.timestamp, 'Media: mintWithSig expired' ); require( bidShares.collaborators.length == bidShares.collabShares.length, 'Media: Arrays do not have the same length' ); for (uint256 i = 0; i < bidShares.collaborators.length; i++) { require( _hasShares(i, bidShares), 'Media: Each collaborator must have a share of the nft' ); } bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _calculateDomainSeparator(), keccak256( abi.encode( Constants.MINT_WITH_SIG_TYPEHASH, data.contentHash, data.metadataHash, bidShares.creator.value, access.mintWithSigNonces[creator]++, sig.deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && creator == recoveredAddress, 'Media: Signature invalid' ); _mintForCreator(recoveredAddress, data, bidShares); } /** * @notice see IMedia */ function auctionTransfer(uint256 tokenId, address recipient) external override { require( msg.sender == access.marketContract, // remove revert string before deployment to mainnet 'Media: only market contract' ); tokens.previousTokenOwners[tokenId] = ownerOf(tokenId); _safeTransfer(ownerOf(tokenId), recipient, tokenId, ''); } /** * @notice see IMedia */ function setAsk(uint256 tokenId, IMarket.Ask memory ask) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).setAsk(tokenId, ask); } /** * @notice see IMedia */ function removeAsk(uint256 tokenId) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).removeAsk(tokenId); } /** * @notice see IMedia */ function setBid(uint256 tokenId, IMarket.Bid memory bid) public override nonReentrant onlyExistingToken(tokenId) { require(msg.sender == bid.bidder, 'Market: Bidder must be msg sender'); IMarket(access.marketContract).setBid(tokenId, bid, msg.sender); } /** * @notice see IMedia */ function removeBid(uint256 tokenId) external override nonReentrant onlyTokenCreated(tokenId) { IMarket(access.marketContract).removeBid(tokenId, msg.sender); } /** * @notice see IMedia */ function acceptBid(uint256 tokenId, IMarket.Bid memory bid) public override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyExistingToken(tokenId) { IMarket(access.marketContract).acceptBid(address(this), tokenId, bid); } /** * @notice Burn a token. * @dev Only callable if the media owner is also the creator. * @param tokenId the ID of the token to burn */ function burn(uint256 tokenId) public override nonReentrant onlyExistingToken(tokenId) onlyApprovedOrOwner(msg.sender, tokenId) { address owner = ownerOf(tokenId); require( tokens.tokenCreators[tokenId] == owner, // remove revert string before deployment to mainnet 'Media: owner is not creator of media' ); _burn(tokenId); } /** * @notice Revoke the approvals for a token. The provided `approve` function is not sufficient * for this protocol, as it does not allow an approved address to revoke it's own approval. * In instances where a 3rd party is interacting on a user's behalf via `permit`, they should * revoke their approval once their task is complete as a best practice. */ function revokeApproval(uint256 tokenId) external override onlyApprovedOrOwner(msg.sender, tokenId) nonReentrant { _approve(address(0), tokenId); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenURI(uint256 tokenId, string calldata tokenURILocal) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyTokenWithContentHash(tokenId) onlyValidURI(tokenURILocal) { _setTokenURI(tokenId, tokenURILocal); emit TokenURIUpdated(tokenId, msg.sender, tokenURILocal); } /** * @notice see IMedia * @dev only callable by approved or owner */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external override nonReentrant onlyApprovedOrOwner(msg.sender, tokenId) onlyTokenWithMetadataHash(tokenId) onlyValidURI(metadataURI) { _setTokenMetadataURI(tokenId, metadataURI); emit TokenMetadataURIUpdated(tokenId, msg.sender, metadataURI); } /** * @notice See IMedia * @dev This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified * for ERC-721. */ function permit( address spender, uint256 tokenId, EIP712Signature memory sig ) public override nonReentrant onlyExistingToken(tokenId) { require( sig.deadline == 0 || sig.deadline >= block.timestamp, // remove revert string before deployment to mainnet 'Media: Permit expired' ); require( spender != address(0), // remove revert string before deployment to mainnet 'Media: spender cannot be 0x0' ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _calculateDomainSeparator(), keccak256( abi.encode( Constants.PERMIT_TYPEHASH, spender, tokenId, access.permitNonces[ownerOf(tokenId)][tokenId]++, sig.deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && ownerOf(tokenId) == recoveredAddress, // remove revert string before deployment to mainnet 'Media: Signature invalid' ); _approve(spender, tokenId); } /* ***************** * Private Functions * ***************** */ /// @notice Returns a bool depicting whether or not the i'th collaborator has shares /// @dev Explain to a developer any extra details /// @param index the "i'th collaborator" /// @param bidShares the bidshares defined for the Collection's NFTs /// @return Boolean that is true if the i'th collaborator has shares for this collection's NFTs function _hasShares(uint256 index, IMarket.BidShares memory bidShares) internal pure returns (bool) { return (bidShares.collabShares[index] != 0); } /** * @notice Creates a new token for `creator`. Its token ID will be automatically * assigned (and available on the emitted {IERC721-Transfer} event), and the token * URI autogenerated based on the base URI passed at construction. * * See {ERC721-_safeMint}. * * On mint, also set the keccak256 hashes of the content and its metadata for integrity * checks, along with the initial URIs to point to the content and metadata. Attribute * the token ID to the creator, mark the content hash as used, and set the bid shares for * the media's market. * * Note that although the content hash must be unique for future mints to prevent duplicate media, * metadata has no such requirement. */ function _mintForCreator( address creator, MediaData memory data, IMarket.BidShares memory bidShares ) internal onlyValidURI(data.tokenURI) onlyValidURI(data.metadataURI) { require(data.contentHash != 0, 'Media: content hash must be non-zero'); require( !access._contentHashes[data.contentHash], 'Media: a token has already been created with this content hash' ); require( data.metadataHash != 0, 'Media: metadata hash must be non-zero' ); uint256 tokenId = access._tokenIdTracker.current(); access._tokenIdTracker.increment(); _safeMint(creator, tokenId); _setTokenContentHash(tokenId, data.contentHash); _setTokenMetadataHash(tokenId, data.metadataHash); _setTokenMetadataURI(tokenId, data.metadataURI); _setTokenURI(tokenId, data.tokenURI); access._creatorTokens[creator].add(tokenId); access._contentHashes[data.contentHash] = true; tokens.tokenCreators[tokenId] = creator; tokens.previousTokenOwners[tokenId] = creator; IMarket(access.marketContract).setBidShares( // address(this), tokenId, bidShares ); IMarket(access.marketContract).mintOrBurn(true, tokenId, address(this)); } function _setTokenContentHash(uint256 tokenId, bytes32 contentHash) internal virtual onlyExistingToken(tokenId) { tokens.tokenContentHashes[tokenId] = contentHash; } function _setTokenMetadataHash(uint256 tokenId, bytes32 metadataHash) internal virtual onlyExistingToken(tokenId) { tokens.tokenMetadataHashes[tokenId] = metadataHash; } function _setTokenMetadataURI(uint256 tokenId, string memory metadataURI) internal virtual onlyExistingToken(tokenId) { access._tokenMetadataURIs[tokenId] = metadataURI; } /** * @notice Destroys `tokenId`. * @dev We modify the OZ _burn implementation to * maintain metadata and to remove the * previous token owner from the piece */ function _burn(uint256 tokenId) internal override(ERC721URIStorageUpgradeable, ERC721Upgradeable) { ERC721URIStorageUpgradeable._burn(tokenId); delete tokens.previousTokenOwners[tokenId]; IMarket(access.marketContract).mintOrBurn( false, tokenId, address(this) ); } /** * @notice transfer a token and remove the ask for it. */ function _transfer( address from, address to, uint256 tokenId ) internal override { IMarket(access.marketContract).removeAsk(tokenId); ERC721Upgradeable._transfer(from, to, tokenId); } /** * @dev Calculates EIP712 DOMAIN_SEPARATOR based on the current contract and chain ID. */ function _calculateDomainSeparator() internal view returns (bytes32) { uint256 chainID; /* solium-disable-next-line */ assembly { chainID := chainid() } return keccak256( abi.encode( kecEIP712Domain, kecName, kecOne, chainID, address(this) ) ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {Decimal} from '../Decimal.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Market */ interface IMarket { struct Bid { // Amount of the currency being bid uint256 amount; // Address to the ERC20 token being used to bid address currency; // Address of the bidder address bidder; // Address of the recipient address recipient; // % of the next sale to award the current owner Decimal.D256 sellOnShare; } struct Ask { // Amount of the currency being asked uint256 amount; // Address to the ERC20 token being asked address currency; } struct BidShares { Decimal.D256 creator; // % of sale value that goes to the seller (current owner) of the nft Decimal.D256 owner; // Array that holds all the collaborators address[] collaborators; // % of sale value that goes to the fourth collaborator of the nft uint256[] collabShares; // Decimal.D256[] collaborators; } struct PlatformFee { // % of sale value that goes to the Vault Decimal.D256 fee; } event BidCreated( address indexed mediaContract, uint256 indexed tokenId, Bid bid ); event BidRemoved( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event BidFinalized( uint256 indexed tokenId, Bid bid, address indexed mediaContract ); event AskCreated( address indexed mediaContract, uint256 indexed tokenId, Ask ask ); event AskRemoved( uint256 indexed tokenId, Ask ask, address indexed mediaContract ); event BidShareUpdated( uint256 indexed tokenId, BidShares bidShares, address indexed mediaContract ); event MediaContractCreated( address indexed mediaContract, bytes32 name, bytes32 symbol ); event Minted(uint256 indexed token, address indexed mediaContract); event Burned(uint256 indexed token, address indexed mediaContract); function bidForTokenBidder( address mediaContractAddress, uint256 tokenId, address bidder ) external view returns (Bid memory); function currentAskForToken(address mediaContractAddress, uint256 tokenId) external view returns (Ask memory); function bidSharesForToken(address mediaContractAddress, uint256 tokenId) external view returns (BidShares memory); function isValidBid( address mediaContractAddress, uint256 tokenId, uint256 bidAmount ) external view returns (bool); function isValidBidShares(BidShares calldata bidShares) external view returns (bool); function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount) external pure returns (uint256); function isRegistered(address mediaContractAddress) external view returns (bool); function configure( address deployer, address mediaContract, bytes32 name, bytes32 symbol ) external; function revokeRegistration(address mediaContract) external; function registerMedia(address mediaContract) external; function setMediaFactory(address _mediaFactory) external; function mintOrBurn( bool isMint, uint256 tokenId, address mediaContract ) external; function setBidShares(uint256 tokenId, BidShares calldata bidShares) external; function setAsk(uint256 tokenId, Ask calldata ask) external; function removeAsk(uint256 tokenId) external; function setBid( uint256 tokenId, Bid calldata bid, address spender ) external; function removeBid(uint256 tokenId, address bidder) external; function acceptBid( address mediaContractAddress, uint256 tokenId, Bid calldata expectedBid ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {Initializable} from '@openzeppelin/contracts/proxy/utils/Initializable.sol'; contract Ownable is Initializable { event OwnershipTransferInitiated( address indexed owner, address indexed appointedOwner ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); address internal owner; address public appointedOwner; /// @dev The Ownable constructor sets the original `owner` of the contract to the sender account. function initialize() public virtual initializer { owner = msg.sender; } function getOwner() external view returns (address) { return owner; } /// @dev Throws if called by any contract other than latest designated caller modifier onlyOwner() { require( msg.sender == owner, 'Ownable: Only owner has access to this function' ); _; } /// @dev Allows the current owner to intiate the transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function initTransferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: Cannot transfer to zero address"); emit OwnershipTransferInitiated(msg.sender, newOwner); appointedOwner = newOwner; } /// @dev Allows new owner to claim the transfer control of the contract function claimTransferOwnership() public { require(appointedOwner != address(0), "Ownable: No ownership transfer have been initiated"); require(msg.sender == appointedOwner, "Ownable: Caller is not the appointed owner of this contract"); emit OwnershipTransferred(owner, msg.sender); owner = appointedOwner; appointedOwner = address(0); } /// @dev Revoke transfer and set appointed owner to 0 address function revokeTransferOwnership() public onlyOwner { appointedOwner = address(0); } } // 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 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.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; /** * @title Math * * Library for non-standard Math functions * NOTE: This file is a clone of the dydx protocol's Math.sol contract. * It was forked from https://github.com/dydxprotocol/solo at commit * 2d8454e02702fe5bc455b848556660629c3cad36. It has two modifications * - uses a newer solidity in the pragma to match the rest of the contract suite of this project. * - Removed `Require.sol` dependency */ library Math { // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target * (numerator / denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return 0 / denominator; } return target * ((numerator - 1) / denominator) + 1; } function to128(uint256 number) internal pure returns (uint128) { require(number<=type(uint128).max, "Math: Unsafe cast to uint128"); uint128 result = uint128(number); return result; } function to96(uint256 number) internal pure returns (uint96) { require(number<=type(uint96).max, "Math: Unsafe cast to uint96"); uint96 result = uint96(number); return result; } function to32(uint256 number) internal pure returns (uint32) { require(number<=type(uint32).max, "Math: Unsafe cast to uint32"); uint32 result = uint32(number); return result; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable { function __ERC721Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Burnable_init_unchained(); } function __ERC721Burnable_init_unchained() internal initializer { } /** * @dev Burns `tokenId`. See {ERC721-_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 require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Storage based implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165StorageUpgradeable is Initializable, ERC165Upgradeable { function __ERC165Storage_init() internal initializer { __ERC165_init_unchained(); __ERC165Storage_init_unchained(); } function __ERC165Storage_init_unchained() internal initializer { } /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return super.supportsInterface(interfaceId) || _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.8.0; import "../ERC721Upgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721Enumerable_init_unchained(); } function __ERC721Enumerable_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 {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.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 = ERC721Upgradeable.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; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable { function __ERC721URIStorage_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721URIStorage_init_unchained(); } function __ERC721URIStorage_init_unchained() internal initializer { } using StringsUpgradeable 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]; } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; pragma experimental ABIEncoderV2; import {IMarket} from './IMarket.sol'; /** * @title Interface for Zap NFT Marketplace Protocol's Media */ interface IMedia { struct EIP712Signature { uint256 deadline; uint8 v; bytes32 r; bytes32 s; } struct MediaData { // A valid URI of the content represented by this token string tokenURI; // A valid URI of the metadata associated with this token string metadataURI; // A KECCAK256 hash of the content pointed to by tokenURI bytes32 contentHash; // A KECCAK256 hash of the content pointed to by metadataURI bytes32 metadataHash; } event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri); event TokenMetadataURIUpdated( uint256 indexed _tokenId, address owner, string _uri ); function initialize( string memory name, string memory symbol, address marketContractAddr, bool permissive, string memory collectionMetadata ) external; /** * @notice Return the metadata URI for a piece of media given the token URI */ function tokenMetadataURI(uint256 tokenId) external view returns (string memory); /** * @notice Mint new media for msg.sender. */ function mint(MediaData calldata data, IMarket.BidShares calldata bidShares) external; /** * @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature. */ function mintWithSig( address creator, MediaData calldata data, IMarket.BidShares calldata bidShares, EIP712Signature calldata sig ) external; /** * @notice Transfer the token with the given ID to a given address. * Save the previous owner before the transfer, in case there is a sell-on fee. * @dev This can only be called by the auction contract specified at deployment */ function auctionTransfer(uint256 tokenId, address recipient) external; /** * @notice Set the ask on a piece of media */ function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external; /** * @notice Remove the ask on a piece of media */ function removeAsk(uint256 tokenId) external; /** * @notice Set the bid on a piece of media */ function setBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Remove the bid on a piece of media */ function removeBid(uint256 tokenId) external; function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external; /** * @notice Revoke approval for a piece of media */ function revokeApproval(uint256 tokenId) external; /** * @notice Update the token URI */ function updateTokenURI(uint256 tokenId, string calldata tokenURI) external; /** * @notice Update the token metadata uri */ function updateTokenMetadataURI( uint256 tokenId, string calldata metadataURI ) external; /** * @notice EIP-712 permit method. Sets an approved spender given a valid signature. */ function permit( address spender, uint256 tokenId, EIP712Signature calldata sig ) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {MediaStorage} from "./libraries/MediaStorage.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract Ownable is Initializable { event OwnershipTransferInitiated( address indexed owner, address indexed appointedOwner ); event OwnershipTransferred(address indexed previousOwner,address indexed newOwner); MediaStorage.Access internal access; address public appointedOwner; /// @dev The Ownable constructor sets the original `access.owner` of the contract to the sender account. function initialize_ownable() internal initializer { access.owner = msg.sender; } function getOwner() external view returns (address) { return access.owner; } /// @dev Throws if called by any contract other than latest designated caller modifier onlyOwner() { require(msg.sender == access.owner, "onlyOwner error: Only Owner of the Contract can make this Call"); _; } function approveToMint(address toApprove) external onlyOwner { access.approvedToMint[toApprove] = true; } function getTokenMetadataURIs(uint256 _tokenId) external view returns (string memory metadataUri) { return access._tokenMetadataURIs[_tokenId]; } function getSigNonces(address _minter) public view returns (uint256 nonce) { return access.mintWithSigNonces[_minter]; } function getPermitNonce(address _user, uint256 _tokenId) public view returns (uint256 nonce){ return access.permitNonces[_user][_tokenId]; } function marketContract() public view returns (address) { return access.marketContract; } /// @dev Allows the current owner to intiate the transfer control of the contract to a newOwner. /// @param newOwner The address to transfer ownership to. function initTransferOwnership(address payable newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: Cannot transfer to zero address"); emit OwnershipTransferInitiated(access.owner, newOwner); appointedOwner = newOwner; } /// @dev Allows new owner to claim the transfer control of the contract function claimTransferOwnership() public { require(appointedOwner != address(0), "Ownable: No ownership transfer have been initiated"); require(msg.sender == appointedOwner, "Ownable: Caller is not the appointed owner of this contract"); emit OwnershipTransferred(access.owner, msg.sender); // where msg.sender == appointedOwner access.owner = appointedOwner; appointedOwner = address(0); } /// @dev Revoke transfer and set appointed owner to 0 address function revokeTransferOwnership() public onlyOwner { appointedOwner = address(0); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {MediaGettersLib} from './libraries/MediaGettersLib.sol'; import {MediaStorage} from './libraries/MediaStorage.sol'; import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol'; /// @title A title that should describe the contract/interface /// @author The name of the author /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details contract MediaGetter is Initializable { using MediaGettersLib for MediaStorage.Tokens; MediaStorage.Tokens internal tokens; function getTokenCreators(uint256 _tokenId) public view returns (address creator) { creator = tokens.getTokenCreators(_tokenId); } function getPreviousTokenOwners(uint256 _tokenId) public view returns (address prevOwner) { prevOwner = tokens.getPreviousTokenOwners(_tokenId); } function getTokenContentHashes(uint256 _tokenId) public view returns (bytes32 contentHash) { contentHash = tokens.getTokenContentHashes(_tokenId); } function getTokenMetadataHashes(uint256 _tokenId) public view returns (bytes32 metadataHash) { metadataHash = tokens.getTokenMetadataHashes(_tokenId); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import {Counters} from '@openzeppelin/contracts/utils/Counters.sol'; import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol'; /// @title A title that should describe the contract/interface /// @author The name of the author /// @notice Explain to an end user what this does /// @dev Explain to a developer any extra details library MediaStorage { using EnumerableSet for EnumerableSet.UintSet; using Counters for Counters.Counter; /* ******* * Globals * ******* */ struct Tokens { // Mapping from token to previous owner of the token mapping(uint256 => address) previousTokenOwners; // Mapping from token id to creator address mapping(uint256 => address) tokenCreators; // Mapping from token id to keccak256 hash of content mapping(uint256 => bytes32) tokenContentHashes; // Mapping from token id to keccak256 hash of metadata mapping(uint256 => bytes32) tokenMetadataHashes; } struct Access { // Address for the market address marketContract; address owner; // Mapping from Media address to whether or not to allow permissive minting bool isPermissive; // Mapping from creator address to their (enumerable) set of created tokens mapping(address => EnumerableSet.UintSet) _creatorTokens; // Mapping from contentHash to bool mapping(bytes32 => bool) _contentHashes; // Mapping from address to token id to permit nonce mapping(address => mapping(uint256 => uint256)) permitNonces; // Mapping from address to mint with sig nonce mapping(address => uint256) mintWithSigNonces; // Mapping from address to boolean; can this address mint? mapping(address => bool) approvedToMint; // Mapping from token id to metadataURI mapping(uint256 => string) _tokenMetadataURIs; Counters.Counter _tokenIdTracker; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; library Constants{ //keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH =keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)"); //keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)"); bytes32 public constant MINT_WITH_SIG_TYPEHASH =keccak256("MintWithSig(bytes32 contentHash,bytes32 metadataHash,uint256 creatorShare,uint256 nonce,uint256 deadline)"); bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x4e222e66; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { 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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^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: GPL-3.0 pragma solidity ^0.8.4; import {MediaStorage} from "./MediaStorage.sol"; library MediaGettersLib { function getTokenCreators(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (address creator) { return self.tokenCreators[_tokenId]; } function getPreviousTokenOwners(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (address prevOwner) { return self.previousTokenOwners[_tokenId]; } function getTokenContentHashes(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (bytes32 contentHash) { return self.tokenContentHashes[_tokenId]; } function getTokenMetadataHashes(MediaStorage.Tokens storage self, uint256 _tokenId) internal view returns (bytes32 metadataHash) { return self.tokenMetadataHashes[_tokenId]; } }
See IMedia This method is loosely based on the permit for ERC-20 tokens in EIP-2612, but modified for ERC-721./ remove revert string before deployment to mainnet remove revert string before deployment to mainnet remove revert string before deployment to mainnet
function permit( address spender, uint256 tokenId, EIP712Signature memory sig ) public override nonReentrant onlyExistingToken(tokenId) { require( sig.deadline == 0 || sig.deadline >= block.timestamp, 'Media: Permit expired' ); require( spender != address(0), 'Media: spender cannot be 0x0' ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _calculateDomainSeparator(), keccak256( abi.encode( Constants.PERMIT_TYPEHASH, spender, tokenId, access.permitNonces[ownerOf(tokenId)][tokenId]++, sig.deadline ) ) ) ); address recoveredAddress = ECDSA.recover(digest, sig.v, sig.r, sig.s); require( recoveredAddress != address(0) && ownerOf(tokenId) == recoveredAddress, 'Media: Signature invalid' ); _approve(spender, tokenId); }
6,322,128
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; /// @title BRZ token Bridge /// @author Solange Gueiros // Inpired on // https://github.com/rsksmart/tokenbridge/blob/master/bridge/contracts/Bridge.sol // https://github.com/DistributedCollective/Bridge-SC/blob/master/sovryn-token-bridge/bridge/contracts/Bridge_v3.sol // AccessControl.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/access/AccessControl.sol // Pausable.sol : https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/contracts/security/Pausable.sol import "./ozeppelin/access/AccessControl.sol"; import "./ozeppelin/security/Pausable.sol"; import "./IBridge.sol"; struct BlockchainStruct { uint256 minTokenAmount; uint256 minBRZFee; // quoteETH_BRZ * gasAcceptTransfer * minGasPrice uint256 minGasPrice; // in Wei bool checkAddress; // to verify is an address is EVM compatible is this blockchain } /** * @dev BRZ token Bridge * * Author: Solange Gueiros * * Smart contract to cross the BRZ token between EVM compatible blockchains. * * The tokens are crossed by TransferoSwiss, the company that controls the issuance of BRZs. * * It uses [Open Zeppelin Contracts] * (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.1.0/) * */ contract Bridge is AccessControl, IBridge, Pausable { address private constant ZERO_ADDRESS = address(0); bytes32 private constant NULL_HASH = bytes32(0); bytes32 public constant MONITOR_ROLE = keccak256("MONITOR_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev DECIMALPERCENT is the representation of 100% using (2) decimal places * 100.00 = percentage accuracy (2) to 100% */ uint256 public constant DECIMALPERCENT = 10000; IERC20 public token; uint256 public totalFeeReceivedBridge; // fee received per Bridge, not for transaction in other blockchain /** * @dev Fee percentage bridge. * * For each amount received in the bridge, a fee percentage is discounted. * This function returns this fee percentage bridge. * Include 2 decimal places. */ uint256 public feePercentageBridge; /** * Estimative for function acceptTransfer: 100000 wei, it can change in EVM cost updates * * It is used to calculate minBRZFee in destination, * which can not accept a BRZ fee less than minBRZFee (per blockchain). */ uint256 public gasAcceptTransfer; /** * @dev the quote of pair ETH / BRZ. * * (1 ETH = the amount of BRZ returned) * * in BRZ in minor unit (4 decimal places). * * It is used to calculate minBRZFee in destination * which can not accept a BRZ fee less than minBRZFee (per blockchain). * */ uint256 public quoteETH_BRZ; mapping(bytes32 => bool) public processed; mapping(string => uint256) private blockchainIndex; BlockchainStruct[] private blockchainInfo; string[] public blockchain; /** * @dev Function called only when the smart contract is deployed. * * Parameters: * - address tokenAddress - address of BRZ token used in this blockchain network * * Actions: * - the transaction's sender will be added in the DEFAULT_ADMIN_ROLE. * - the token will be defined by the parameter tokenAddress * - the feePercentageBridge default value is be setted in 10, which means 0.1% */ constructor(address tokenAddress) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); token = IERC20(tokenAddress); feePercentageBridge = 10; //0.1% gasAcceptTransfer = 100000; //Estimative function acceptTransfer: 100000 wei } /** * @dev Modifier which verifies if the caller is an owner, * it means he has the role `DEFAULT_ADMIN_ROLE`. * * The role `DEFAULT_ADMIN_ROLE` is defined by Open Zeppelin's AccessControl smart contract. * * By default (setted in the constructor) the account which deployed this smart contract is in this role. * * This owner can add / remove other owners. */ modifier onlyOwner() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "not owner"); _; } /** * @dev Modifier which verifies if the caller is a monitor, * it means he has the role `MONITOR_ROLE`. * * Role MONITOR are referred to its `bytes32` identifier, * defined in the `public constant` called MONITOR_ROLE. * It should be exposed in the external API and be unique. * * Role MONITOR is used to manage the permissions of monitor's addresses. */ modifier onlyMonitor() { require(hasRole(MONITOR_ROLE, _msgSender()), "not monitor"); _; } /** * @dev Modifier which verifies if the caller is a monitor, * it means he has the role `ADMIN_ROLE`. * * Role ADMIN are referred to its `bytes32` identifier, * defined in the `public constant` called ADMIN_ROLE. * It should be exposed in the external API and be unique. * * Role ADMIN is used to manage the permissions for update minimum fee per blockchain. */ modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "not admin"); _; } /** * @dev Function which returns the bridge's version. * * This is a fixed value define in source code. * * Parameters: none * * Returns: string */ function version() external pure override returns (string memory) { return "v0"; } /** * @dev Private function to compare two strings * and returns `true` if the strings are equal, * otherwise it returns false. * * Parameters: stringA, stringB * * Returns: bool */ function compareStrings(string memory a, string memory b) private pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } /** * @dev This function starts the process of crossing tokens in the Bridge. * * > Any account / person can call it! * * Can not be called if the Bridge is paused. * * Parameters: * - amount - gross amount of tokens to be crossed. * - The Bridge fee will be deducted from this amount. * - transactionFee - array with the fees: * - transactionFee[0] - fee in BRL - this fee will be added to amount transfered from caller's account. * - transactionFee[1] - gas price for fee in destiny currency(minor unit) - this information will be * used in the destination Blockchain, * by the monitor who will create the transaction and send using this fee defined here. * - toBlockchain - the amount will be sent to this blockchain. * - toAddress - the amount will be sent to this address. It can be diferent from caller's address. * This is a string because some blockchain could not have the same pattern from Ethereum / RSK / BSC. * * Returns: bool - true if it is sucessful. * * > Before call this function, the caller MUST have called function `approve` in BRZ token, * > allowing the bridge's smart contract address to use the BRZ tokens, * > calling the function `transferFrom`. * * References: * * ERC-20 tokens approve and transferFrom pattern: * [eip-20#transferfrom](https://eips.ethereum.org/EIPS/eip-20#transferfrom) * * Requirements: * - fee in BRZ (transactionFee[0]) must be at least (BRZFactorFee[blockchainName] * minGasPrice[toBlockchain]). * - gasPrice (transactionFee[1]) in destiny blockchain (minor unit) greater than minGasPrice in toBlockchain. * - toBlockchain exists. * - toAddress is not an empty string. * - amount must be greater than minTokenAmount in toBlockchain. * - amount greater than zero. * * Actions: * - add the blockchain fee in BRZ to amount in BRZ, in totalAmount. * - calculate bridge's fee using the original amount to be sent. * - discount bridge's fee from the original amount, in amountMinusFees. * - add bridge's fee to `totalFeeReceivedBridge`, a variable to store all the fees received by the bridge. * - BRZ transfer totalAmount from the caller's address to bridge address. * - emit `CrossRequest` event, with the parameters: * - from - address of the caller's function. * - amount - the net amount to be transfered in the destination blockchain. * - toFee - the gas price fee, which must be used to send the transfer transaction in the destination blockchain. * - toAddress - string representing the address which will receive the tokens. * - toBlockchain - the destination blockchain. * * > The `CrossRequest` event is very important because it must be listened by the monitor, * an external program which will * send the transaction on the destination blockchain. * * #### More info about fees * * - Blockchain / transaction fee in BRL (transactionFee[0]) * It will be transfered from user's account, * along with the amount he would like to receive in the account. * * This will be spent in `toBlockchain`. * Does not depend of amount, but of destination blockchain. * * It must be at least the minBRZFee per blockchain. * * It is used in the function acceptTransfer, * which can not accept a BRZ fee less than minBRZFee (per blockchain). * * - gas price (transactionFee[1]) * It must be at least the minGasPrice per blockchain. * * - Bridge Fee - it is deducted from the requested amount. * It is a percentage of the requested amount. * Cannot include the transaction fee in order to be calculated. * */ function receiveTokens( uint256 amount, uint256[2] memory transactionFee, string memory toBlockchain, string memory toAddress ) external override whenNotPaused returns (bool) { require(existsBlockchain(toBlockchain), "toBlockchain not exists"); require(!compareStrings(toAddress, ""), "toAddress is null"); uint256 index = blockchainIndex[toBlockchain] - 1; require( transactionFee[0] >= blockchainInfo[index].minBRZFee, "feeBRZ is less than minimum" ); require( transactionFee[1] >= blockchainInfo[index].minGasPrice, "gasPrice is less than minimum" ); require(amount > 0, "amount is 0"); require( amount >= blockchainInfo[index].minTokenAmount, "amount is less than minimum" ); if (blockchainInfo[index].checkAddress) { require(bytes(toAddress).length == 42, "invalid destination address"); } //The total amount is the amount desired plus the blockchain fee to destination, in the token unit uint256 totalAmount = amount + transactionFee[0]; //Bridge fee or service fee uint256 bridgeFee = (amount * feePercentageBridge) / DECIMALPERCENT; uint256 amountMinusFees = amount - bridgeFee; totalFeeReceivedBridge += bridgeFee; //This is the message for Monitor off-chain manage the transaction and send the tokens on the other Blockchain emit CrossRequest( _msgSender(), amountMinusFees, transactionFee[1], toAddress, toBlockchain ); //Transfer the tokens on IERC20, they should be already approved for the bridge Address to use them token.transferFrom(_msgSender(), address(this), totalAmount); return true; } /** * @dev This function calculate a transaction id hash. * * Any person can call it. * * Parameters: * - hashes - from transaction in the origin blockchain: * - blockHash - hash of the block where was the transaction `receiveTokens` * - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`. * - receiver - the address which will receive the tokens. * - amount - the net amount to be transfered. * - logIndex - the index of the event `CrossRequest` in the logs of transaction. * - sender - address who sent the transaction `receiveTokens`, it is a string to be compatible with any blockchain. * * Returns: a bytes32 hash of all the information sent. * * Notes: * It did not use origin blockchain and sender address * because the possibility of having the same origin transaction from different blockchain source is minimal. * * It is a point to be evaluated in an audit. * */ function getTransactionId( bytes32[2] calldata hashes, //blockHash, transactionHash address receiver, uint256 amount, uint32 logIndex ) public pure override returns (bytes32) { return keccak256( abi.encodePacked(hashes[0], hashes[1], receiver, amount, logIndex) ); } /** * @dev This function update the variable processed for a transaction * * > Only monitor can call it! * * This variable is a public mapping. * * Each bytes32 which represents a Transaction Id has his boolen value stored. * */ function _processTransaction( bytes32[2] calldata hashes, //blockHash, transactionHash address receiver, uint256 amount, uint32 logIndex ) private { bytes32 transactionId = getTransactionId( hashes, receiver, amount, logIndex ); require(!processed[transactionId], "processed"); processed[transactionId] = true; } /** * @dev This function transfer tokens from the the internal balance of bridge smart contract * to the internal balance of the destination address. * * The token.balanceOf(bridgeAddress) must always be greather than or equal the total amount to be claimed by users, * as there may be tokens not yet claimed. * * Can not be called if the Bridge is paused. * * > Only monitor can call it! * */ function _sendToken(address to, uint256 amount) private returns (bool) { require(token.balanceOf(address(this)) >= amount, "insufficient balance"); token.transfer(to, amount); return true; } /** * @dev This function accept the cross of token, * which means it is called in the destination blockchain, * who will send the tokens accepted to be crossed. * * > Only monitor can call it! * * Can not be called if the Bridge is paused. * * Parameters: * - receiver - the address which will receive the tokens. * - amount - the net amount to be transfered. * - sender - string representing the address of the token's sender. * - fromBlockchain - the origin blockchain. * - hashes - from transaction in the origin blockchain: * - blockHash - hash of the block where was the transaction `receiveTokens`. * - transactionHash - hash of the transaction `receiveTokens` with the event `CrossRequest`. * - logIndex - the index of the event `CrossRequest` in the transaction logs. * * Returns: bool - true if it is sucessful * * Requirements: * - receiver is not a zero address. * - amount greater than zero. * - sender is not an empty string. * - fromBlockchain exists. * - blockHash is not null hash. * - transactionHash is not hash. * * Actions: * - processTransaction: * - getTransactionId * - verify if the transactionId was already processed * - update the status processed for transactionId * - sendToken: * - check if the bridge has in his balance at least the amount required to do the transfer * - transfer the amount tokens to destination address * */ function acceptTransfer( address receiver, uint256 amount, string calldata fromBlockchain, bytes32[2] calldata hashes, //blockHash, transactionHash uint32 logIndex ) external override onlyMonitor whenNotPaused returns (bool) { require(receiver != ZERO_ADDRESS, "receiver is zero"); require(amount > 0, "amount is 0"); require(existsBlockchain(fromBlockchain), "fromBlockchain not exists"); require(hashes[0] != NULL_HASH, "blockHash is null"); require(hashes[1] != NULL_HASH, "transactionHash is null"); _processTransaction(hashes, receiver, amount, logIndex); _sendToken(receiver, amount); return true; } /** * @dev Returns token balance in bridge. * * Parameters: none * * Returns: integer amount of tokens in bridge * */ function getTokenBalance() external view override returns (uint256) { return token.balanceOf(address(this)); } /** * @dev Withdraw tokens from bridge * * Only owner can call it. * * Can be called even if the Bridge is paused, * because can happens a problem and it is necessary to withdraw tokens, * maybe to create a new version of bridge, for example. * * The tokens only can be sent to the caller's function. * * Parameters: integer amount of tokens * * Returns: true if it is successful * * Requirements: * - amount less or equal balance of tokens in bridge. * */ function withdrawToken(uint256 amount) external onlyOwner returns (bool) { require(amount <= token.balanceOf(address(this)), "insuficient balance"); token.transfer(_msgSender(), amount); return true; } /** * @dev This function add an address in the `MONITOR_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of monitor to be added * * Returns: bool - true if it is sucessful * */ function addMonitor(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(ADMIN_ROLE, account), "is admin"); grantRole(MONITOR_ROLE, account); return true; } /** * @dev This function excludes an address in the `MONITOR_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of monitor to be excluded * * Returns: bool - true if it is sucessful * */ function delMonitor(address account) external onlyOwner whenNotPaused returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE revokeRole(MONITOR_ROLE, account); return true; } /** * @dev This function add an address in the `ADMIN_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of admin to be added * * Returns: bool - true if it is sucessful * */ function addAdmin(address account) external onlyOwner whenNotPaused returns (bool) { require(!hasRole(MONITOR_ROLE, account), "is monitor"); grantRole(ADMIN_ROLE, account); return true; } /** * @dev This function excludes an address in the `ADMIN_ROLE`. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of admin to be excluded * * Returns: bool - true if it is sucessful * */ function delAdmin(address account) external onlyOwner whenNotPaused returns (bool) { //Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE revokeRole(ADMIN_ROLE, account); return true; } /** * @dev This function allows a user to renounce a role * * Parameters: bytes32 role, address account * * Returns: none * * Requirements: * * - An owner can not renounce the role DEFAULT_ADMIN_ROLE. * - Can only renounce roles for your own account. * */ function renounceRole(bytes32 role, address account) public virtual override { require(role != DEFAULT_ADMIN_ROLE, "can not renounce role owner"); require(account == _msgSender(), "can only renounce roles for self"); super.renounceRole(role, account); } /** * @dev This function allows to revoke a role * * Parameters: bytes32 role, address account * * Returns: none * * Requirements: * * - An owner can not revoke yourself in the role DEFAULT_ADMIN_ROLE. * */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { if (role == DEFAULT_ADMIN_ROLE) { require(account != _msgSender(), "can not revoke yourself in role owner"); } super.revokeRole(role, account); } /** * @dev This function update the minimum blockchain fee - gas price - in the minor unit. * * It is an internal function, called when quoteETH_BRZ, gasAcceptTransfer * * Returns: bool - true if it is sucessful * * Emit the event `MinBRZFeeChanged(blockchain, oldFee, newFee)`. * */ function _updateMinBRZFee() internal returns (bool) { for (uint8 i = 0; i < blockchainInfo.length; i++) { if (blockchainInfo[i].minGasPrice > 0) { uint256 newFee = (gasAcceptTransfer * blockchainInfo[i].minGasPrice * quoteETH_BRZ) / (1 ether); emit MinBRZFeeChanged( blockchain[i], blockchainInfo[i].minBRZFee, newFee ); blockchainInfo[i].minBRZFee = newFee; } } return true; } /** * @dev This function update quote of pair ETH / BRZ. * * (1 ETH = the amount of BRZ defined) * * Only admin can call it. * * Each time quoteETH_BRZ is updated, the MinBRZFee is updated too. * * Parameters: integer, the new quote * * Returns: bool - true if it is sucessful * * Emit the event `QuoteETH_BRZChanged(oldValue, newValue)`. * */ function setQuoteETH_BRZ(uint256 newValue) public onlyAdmin returns (bool) { emit QuoteETH_BRZChanged(quoteETH_BRZ, newValue); quoteETH_BRZ = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } /** * @dev Returns the minimum gas price to cross tokens. * * The function acceptTransfer can not accept less than the minimum gas price per blockchain. * * Parameters: string, blockchain name * * Returns: integer * */ function getMinGasPrice(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minGasPrice; } /** * @dev This function update the minimum blockchain fee - gas price - in the minor unit. * * Each time setMinGasPrice is updated, the MinBRZFee is updated too. * * Only admin can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new fee * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain must exists. * * Emit the event `MinGasPriceChanged(blockchain, oldFee, newFee)`. * */ function setMinGasPrice(string memory blockchainName, uint256 newFee) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinGasPriceChanged( blockchainName, blockchainInfo[index].minGasPrice, newFee ); blockchainInfo[index].minGasPrice = newFee; blockchainInfo[index].minBRZFee = (gasAcceptTransfer * newFee * quoteETH_BRZ) / (1 ether); return true; } /** * @dev Returns the minimum destination blockchain fee in BRZ, * in minor unit (4 decimal places) * * It is updated when one of these itens be updated: * - gasAcceptTransfer * - quoteETH_BRZ * - minGasPrice per Blockchain * * It is used in the function acceptTransfer, * which can not accept a BRZ fee less than minBRZFee (per blockchain). * * Parameters: string, blockchain name * * Returns: integer * */ function getMinBRZFee(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minBRZFee; } /** * @dev This function update the estimative of the gas amount used in function AcceptTransfer. * * It will only change if happen some EVM cost update. * * Only owner can call it. * * Each time gasAcceptTransfer is updated, the MinBRZFee is updated too. * * Parameters: integer, the new gas amount * * Returns: bool - true if it is sucessful * * Emit the event `GasAcceptTransferChanged(oldValue, newValue)`. * */ function setGasAcceptTransfer(uint256 newValue) public onlyOwner returns (bool) { emit GasAcceptTransferChanged(gasAcceptTransfer, newValue); gasAcceptTransfer = newValue; require(_updateMinBRZFee(), "updateMinBRZFee error"); return true; } /** * @dev Returns the minimum token amount to cross. * * The function acceptTransfer can not accpept less than the minimum per blockchain. * * Parameters: string, blockchain name * * Returns: integer * */ function getMinTokenAmount(string memory blockchainName) external view override returns (uint256) { return blockchainInfo[blockchainIndex[blockchainName] - 1].minTokenAmount; } /** * @dev This function update the minimum token's amount to be crossed. * * Only admin can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new amount * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain must exists. * * Emit the event `MinTokenAmountChanged(blockchain, oldMinimumAmount, newMinimumAmount)`. * */ function setMinTokenAmount(string memory blockchainName, uint256 newAmount) public onlyAdmin whenNotPaused returns (bool) { require(existsBlockchain(blockchainName), "blockchain not exists"); uint256 index = blockchainIndex[blockchainName] - 1; emit MinTokenAmountChanged( blockchainName, blockchainInfo[index].minTokenAmount, newAmount ); blockchainInfo[index].minTokenAmount = newAmount; return true; } /** * @dev This function update the fee percentage bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: integer, the new fee * * Returns: bool - true if it is sucessful * * Requirements: * - The new fee must be lower than 10% . * * Emit the event `FeePercentageBridgeChanged(oldFee, newFee)`. * */ function setFeePercentageBridge(uint256 newFee) external onlyOwner whenNotPaused returns (bool) { require(newFee < (DECIMALPERCENT / 10), "bigger than 10%"); emit FeePercentageBridgeChanged(feePercentageBridge, newFee); feePercentageBridge = newFee; return true; } /** * @dev This function update the BRZ token. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: address of new BRZ token * * Returns: bool - true if it is sucessful * * Requirements: * - The token address must not be a zero address. * * Emit the event `TokenChanged(tokenAddress)`. * */ function setToken(address tokenAddress) external onlyOwner whenNotPaused returns (bool) { require(tokenAddress != ZERO_ADDRESS, "zero address"); emit TokenChanged(tokenAddress); token = IERC20(tokenAddress); return true; } /** * @dev Returns if a blockchain is in the list of allowed blockchains to cross tokens using the bridge. * * Parameters: string name of blockchain * * Returns: boolean true if it is in the list * */ function existsBlockchain(string memory name) public view override returns (bool) { if (blockchainIndex[name] == 0) return false; else return true; } /** * @dev List of blockchains allowed to cross tokens using the bridge. * * Parameters: none * * Returns: an array of strings containing the blockchain list * */ function listBlockchain() external view override returns (string[] memory) { return blockchain; } /** * @dev This function include a new blockchain in the list of allowed blockchains used in the bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: * - string name of blockchain to be added * - minGasPrice * - minTokenAmount * - check address EVM compatible * * Returns: index of blockchain. * * Important: * - index start in 1, not 0. * - index 0 means that the blockchain does no exist. * - index 1 means that it is the position 0 in the array. * * Requirements: * - blockchain not exists. * - onlyOwner * - whenNotPaused */ function addBlockchain( string memory name, uint256 minGasPrice, uint256 minTokenAmount, bool checkAddress ) external onlyOwner whenNotPaused returns (uint256) { require(!existsBlockchain(name), "blockchain exists"); BlockchainStruct memory b; b.minGasPrice = minGasPrice; b.minTokenAmount = minTokenAmount; b.minBRZFee = (gasAcceptTransfer * minGasPrice * quoteETH_BRZ) / (1 ether); b.checkAddress = checkAddress; blockchainInfo.push(b); blockchain.push(name); uint256 index = blockchainInfo.length; blockchainIndex[name] = index; return (index); } /** * @dev This function exclude a blockchain in the list of allowed blockchains used in the bridge. * * Only owner can call it. * * Can not be called if the Bridge is paused. * * Parameters: string name of blockchain to be excluded * * Returns: bool - true if it is sucessful * * Requirements: * - blockchain exists. * - there must be at least one blockchain left. * */ function delBlockchain(string memory name) external onlyOwner whenNotPaused returns (bool) { require(existsBlockchain(name), "blockchain not exists"); require(blockchainInfo.length > 1, "requires at least 1 blockchain"); uint256 indexToDelete = blockchainIndex[name] - 1; uint256 indexToMove = blockchainInfo.length - 1; //string memory keyToMove = blockchainInfo[indexToMove].name; string memory keyToMove = blockchain[indexToMove]; blockchainInfo[indexToDelete] = blockchainInfo[indexToMove]; blockchain[indexToDelete] = blockchain[indexToMove]; blockchainIndex[keyToMove] = indexToDelete + 1; delete blockchainIndex[name]; blockchainInfo.pop(); blockchain.pop(); return true; } /** * @dev This function pauses the bridge. * * Only owner can call it. * * Parameters: none * * Returns: none * * Requirements: * * - The contract must not be paused. * */ function pause() external onlyOwner { /** * @dev See {Pausable-_pause}. * * Requirements: * * - The contract must not be paused. */ _pause(); } /** * @dev This function unpauses the bridge. * * Only owner can call it. * * Parameters: none * * Returns: none * * Requirements: * * - The contract must be paused. */ function unpause() external onlyOwner { /** * @dev See {Pausable-_unpause}. * * Requirements: * * - The contract must be paused. */ _unpause(); } }
This function excludes an address in the `MONITOR_ROLE`. Only owner can call it. Can not be called if the Bridge is paused. Parameters: address of monitor to be excluded Returns: bool - true if it is sucessful/Can be called only by the account defined in constructor: DEFAULT_ADMIN_ROLE
function delMonitor(address account) external onlyOwner whenNotPaused returns (bool) { revokeRole(MONITOR_ROLE, account); return true; }
12,927,588
./full_match/1/0xAEf566ca7E84d1E736f999765a804687f39D9094/sources/@equilibria/root/control/unstructured/UOwnable.sol
Initializes the contract setting `msg.sender` as the initial owner/
function __UOwnable__initialize() internal onlyInitializer { _updateOwner(msg.sender); }
17,012,354
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./InterfaceBabyTigers.sol"; contract BabyTigersManager is ReentrancyGuard, Ownable { // Contracts address public babyTigersAddress; InterfaceBabyTigers babyTigersContract; address public typicalTigersAddress; IERC721Enumerable typicalTigersContract; // Sale Status bool public holderSaleIsActive = false; mapping(uint256 => bool) public claimedTypicalTigers; // Events event HolderSaleActivation(bool isActive); event BabyTigersManagerChanged(address newManager); constructor(address _typicalTigersAddress, address _babyTigersAddress) { babyTigersAddress = _babyTigersAddress; babyTigersContract = InterfaceBabyTigers(_babyTigersAddress); typicalTigersAddress = _typicalTigersAddress; typicalTigersContract = IERC721Enumerable(_typicalTigersAddress); } //Holder status validation function isTypicalTigerAvailable(uint256 _tokenId) public view returns(bool) { bool isAvailableOnBabyTigersContract = babyTigersContract.isTypicalTigerAvailable(_tokenId); return claimedTypicalTigers[_tokenId] != true && isAvailableOnBabyTigersContract; } // Minting function ownerMint(address _to, uint256 _count) external onlyOwner { babyTigersContract.ownerMint(_to, _count); } function holderMint(uint256[] calldata _typicalTigerIds, uint256 _count) external nonReentrant { require(holderSaleIsActive, "HOLDER_SALE_INACTIVE"); require( _count == _typicalTigerIds.length, "INSUFFICIENT_TT_TOKENS" ); require(typicalTigersContract.balanceOf(msg.sender) > 0, "NO_TT_TOKENS"); for (uint256 i = 0; i < _typicalTigerIds.length; i++) { require(isTypicalTigerAvailable(_typicalTigerIds[i]), "TT_ALREADY_CLAIMED"); require(typicalTigersContract.ownerOf(_typicalTigerIds[i]) == msg.sender, "NOT_TT_OWNER"); claimedTypicalTigers[_typicalTigerIds[i]] = true; } babyTigersContract.ownerMint(msg.sender, _count); } // This should toggle holderSaleIsActive in the manager contract's storage function toggleHolderSaleStatus() external onlyOwner { holderSaleIsActive = !holderSaleIsActive; emit HolderSaleActivation(holderSaleIsActive); } function toggleWhitelistSaleStatus() external onlyOwner { babyTigersContract.toggleWhitelistSaleStatus(); } function toggleSaleStatus() external onlyOwner { babyTigersContract.toggleSaleStatus(); } function setMintPrice(uint256 _mintPrice) external onlyOwner { babyTigersContract.setMintPrice(_mintPrice); } function setWhitelistMintPrice(uint256 _mintPrice) external onlyOwner { babyTigersContract.setWhitelistMintPrice(_mintPrice); } function setMaxPurchase(uint256 _maxPurchase) external onlyOwner { babyTigersContract.setMaxPurchase(_maxPurchase); } function lockMetadata() external onlyOwner { babyTigersContract.lockMetadata(); } function withdraw() external onlyOwner { babyTigersContract.withdraw(); payable(owner()).transfer(address(this).balance); } function setBaseURI(string memory baseURI) external onlyOwner { babyTigersContract.setBaseURI(baseURI); } function setMerkleRoot(bytes32 _root) external onlyOwner { babyTigersContract.setMerkleRoot(_root); } function transferBabyTigersOwnership(address _newOwner) external onlyOwner { require(_newOwner != address(0), "NO_ADDRESS_PROVIDED"); babyTigersContract.transferOwnership(_newOwner); emit BabyTigersManagerChanged(_newOwner); } receive() external payable virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view override returns (address) { return _roleMembers[role].at(index); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {grantRole} to track enumerable memberships */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {revokeRole} to track enumerable memberships */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {renounceRole} to track enumerable memberships */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { super.renounceRole(role, account); _roleMembers[role].remove(account); } /** * @dev Overload {_setupRole} to track enumerable memberships */ function _setupRole(bytes32 role, address account) internal virtual override { super._setupRole(role, account); _roleMembers[role].add(account); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; interface InterfaceBabyTigers is IERC721 { // Events event SaleActivation(bool isActive); event HolderSaleActivation(bool isActive); event WhitelistSaleActivation(bool isActive); // Merkle Proofs function setMerkleRoot(bytes32 _root) external; function isWhitelisted( address _account, bytes32[] calldata _proof ) external view returns (bool); //Holder status validation function isTypicalTigerAvailable(uint256 _tokenId) external view returns(bool); // Minting function ownerMint(address _to, uint256 _count) external; function holderMint(uint256[] calldata _typicalTigerIds, uint256 _count) external; function whitelistMint( uint256 _count, bytes32[] calldata _proof ) external payable; function mint(uint256 _count) external payable; function toggleHolderSaleStatus() external; function toggleWhitelistSaleStatus() external; function toggleSaleStatus() external; function setMintPrice(uint256 _mintPrice) external; function setWhitelistMintPrice(uint256 _mintPrice) external; function setMaxPurchase(uint256 _maxPurchase) external; function lockMetadata() external; function withdraw() external; function transferOwnership(address newOwner) external; function getWalletOfOwner(address owner) external view returns (uint256[] memory); function getTotalSupply() external view returns (uint256); function setBaseURI(string memory baseURI) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) external view returns (address); /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; } }
This should toggle holderSaleIsActive in the manager contract's storage
function toggleHolderSaleStatus() external onlyOwner { holderSaleIsActive = !holderSaleIsActive; emit HolderSaleActivation(holderSaleIsActive); }
283,438
./partial_match/1/0xa6d8C77FFf3CDcc43804275aD9997b603a7817c5/sources/src/libraries/ButtonswapLibrary.sol
Given an output amount of an asset and pair pools, returns a required input amount of the other asset amountOut The output amount of the asset poolIn The balance of the input asset in the pool poolOut The balance of the output asset in the pool return amountIn The required input amount of the other asset/
function getAmountIn(uint256 amountOut, uint256 poolIn, uint256 poolOut) internal pure returns (uint256 amountIn) { if (amountOut == 0) { revert InsufficientOutputAmount(); } if (poolIn == 0 || poolOut == 0) { revert InsufficientLiquidity(); } uint256 numerator = poolIn * amountOut * 1000; uint256 denominator = (poolOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; }
3,642,149
./partial_match/1/0x898a2f629Bf44eBE9B76Ff0EC3A63C2519C8881f/sources/1.EGGMAN.sol
==== Calculate amount of tokens to be transfered ====
function calculateTransferAmount(address from, address to, uint256 amount) internal returns (uint256 transferAmount, uint256 taxAmount) { transferAmount = amount; taxAmount = 0; NewWLTaxRate = 0; }
4,382,357
./partial_match/1/0xDC8d77b69155c7E68A95a4fb0f06a71FF90B943a/sources/src/libraries/PendingOwnable.sol
Returns the address of the current pending owner return The address of the current pending owner/
function pendingOwner() public view override returns (address) { return _pendingOwner; }
3,665,287
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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); } } } } // Part: OpenZeppelin/[email protected]/Context /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with 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; } } // Part: OpenZeppelin/[email protected]/Counters /** * @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; } } // Part: OpenZeppelin/[email protected]/IAccessControl /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // Part: OpenZeppelin/[email protected]/IERC165 /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @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); } // Part: OpenZeppelin/[email protected]/ReentrancyGuard /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Part: OpenZeppelin/[email protected]/Strings /** * @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); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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); } } // Part: OpenZeppelin/[email protected]/Pausable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // Part: OpenZeppelin/[email protected]/AccessControl /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // Part: OpenZeppelin/[email protected]/Escrow /** * @title Escrow * @dev Base escrow contract, holds funds designated for a payee until they * withdraw them. * * Intended usage: This contract (and derived escrow contracts) should be a * standalone contract, that only interacts with the contract that instantiated * it. That way, it is guaranteed that all Ether will be handled according to * the `Escrow` rules, and there is no need to check for payable functions or * transfers in the inheritance tree. The contract that uses the escrow as its * payment method should be its owner, and provide public methods redirecting * to the escrow's deposit and withdraw. */ contract Escrow is Ownable { using Address for address payable; event Deposited(address indexed payee, uint256 weiAmount); event Withdrawn(address indexed payee, uint256 weiAmount); mapping(address => uint256) private _deposits; function depositsOf(address payee) public view returns (uint256) { return _deposits[payee]; } /** * @dev Stores the sent amount as credit to be withdrawn. * @param payee The destination address of the funds. */ function deposit(address payee) public payable virtual onlyOwner { uint256 amount = msg.value; _deposits[payee] += amount; emit Deposited(payee, amount); } /** * @dev Withdraw accumulated balance for a payee, forwarding all gas to the * recipient. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee The address whose funds will be withdrawn and transferred to. */ function withdraw(address payable payee) public virtual onlyOwner { uint256 payment = _deposits[payee]; _deposits[payee] = 0; payee.sendValue(payment); emit Withdrawn(payee, payment); } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @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 {} } // Part: OpenZeppelin/[email protected]/PullPayment /** * @dev Simple implementation of a * https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment] * strategy, where the paying contract doesn't interact directly with the * receiver account, which must withdraw its payments itself. * * Pull-payments are often considered the best practice when it comes to sending * Ether, security-wise. It prevents recipients from blocking execution, and * eliminates reentrancy concerns. * * 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]. * * To use, derive from the `PullPayment` contract, and use {_asyncTransfer} * instead of Solidity's `transfer` function. Payees can query their due * payments with {payments}, and retrieve them with {withdrawPayments}. */ abstract contract PullPayment { Escrow private immutable _escrow; constructor() { _escrow = new Escrow(); } /** * @dev Withdraw accumulated payments, forwarding all gas to the recipient. * * Note that _any_ account can call this function, not just the `payee`. * This means that contracts unaware of the `PullPayment` protocol can still * receive funds this way, by having a separate account call * {withdrawPayments}. * * WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities. * Make sure you trust the recipient, or are either following the * checks-effects-interactions pattern or using {ReentrancyGuard}. * * @param payee Whose payments will be withdrawn. */ function withdrawPayments(address payable payee) public virtual { _escrow.withdraw(payee); } /** * @dev Returns the payments owed to an address. * @param dest The creditor's address. */ function payments(address dest) public view returns (uint256) { return _escrow.depositsOf(dest); } /** * @dev Called by the payer to store the sent amount as credit to be pulled. * Funds sent in this way are stored in an intermediate {Escrow} contract, so * there is no danger of them being spent before withdrawal. * * @param dest The destination address of the funds. * @param amount The amount to transfer. */ function _asyncTransfer(address dest, uint256 amount) internal virtual { _escrow.deposit{value: amount}(dest); } } // Part: OpenZeppelin/[email protected]/ERC721Burnable /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_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 require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // Part: OpenZeppelin/[email protected]/ERC721Enumerable /** * @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(); } } // Part: OpenZeppelin/[email protected]/ERC721URIStorage /** * @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]; } } } // Part: RPSCollectible /// @title Scissors Contract. /// Contract by RpsNft_Art /// Contract created by: (SHA-256) d735dfa8fa552fcb02c42894edebb4652d44697d1636b6125d2367caf2ade334 abstract contract RPSCollectible is ERC721, ERC721URIStorage, ERC721Enumerable, ERC721Burnable, Ownable, Pausable, AccessControl, PullPayment, ReentrancyGuard { // Events Declaration event preSales(bool on_off); event preSalesCompleted(); event baseURIChanged(string _baseURI); event maxPreSalesReached(uint256 _maxPresales); event maxWhiteListReached(uint256 _maxWhiteList); event maxPublicSalesReached(uint256 _maxDrop); // Usings using Counters for Counters.Counter; using Address for address; // isContract() using Strings for uint256; // toString() // Counters Counters.Counter internal _tokenIdCounter; Counters.Counter internal _presalesCounter; // Keep track of per-wallet minting amounts during pre-sales mapping(address => uint256) internal _preSalesMinted; // Keep track of per-wallet minting amounts for white lists mapping(address => uint256) internal _whiteListMinted; // WhiteList controls uint256 private wlAllocatedAmount = 0; bool private wlAllocated = false; string internal _baseTokenURI; uint256 internal maxDrop;// = eg. 10000; uint256 internal preSalesMintPrice; // = In Weis e.g 55000000000000000; uint256 internal mintPrice; // = In Weis e.g. 75000000000000000; uint256 internal maxPresales; // = e.g 3000 uint256 internal maxPresalesNFTAmount; // = e.g 2 uint256 internal maxWhiteListNFTAmount; // = e.g 5 uint256 internal maxSalesNFTAmount; // e.g 25 uint256 internal maxWhiteListAmount; // e.g 150; bool internal _inPresalesMode = false; bool internal _preSalesFinished = false; bool internal _publicSalesFinished = false; // List Roles bytes32 public constant PRESALES_ROLE = keccak256("RPS_PRESALES"); bytes32 public constant WHITELIST_ROLE = keccak256("RPS_WHITELIST"); /** * * Constructor : Owner created * */ constructor(string memory _name, string memory _symbol) ERC721(_name,_symbol) AccessControl() { // super constructors require(!(msg.sender.isContract())); // dev: The address is not an account // set initial flags as false // (not in presales, presales not finished and public sales not finished) _inPresalesMode = false; _preSalesFinished = false; _publicSalesFinished = false; // do not allow minting to begin with preSalesOff(); pause(); // msg.sender (owner) is the root and admin _presalesCounter.reset(); _tokenIdCounter.reset(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); // Init white list wlAllocatedAmount = 0; wlAllocated = false; } /** ---- ANYONE CAN CALL, SOME EXTERNAL ONLY ---- */ /** * Returns number of white list allocated */ function getWlAllocatedAmount() public view returns(uint256) { return(wlAllocatedAmount); } /** * * Returns whether or not the contract is in preSales mode * */ function inPresales() public view returns(bool) { return (_inPresalesMode && !_preSalesFinished); } /** * * Returns whether or not the contract is in public Sales mode * */ function inPublicSales() public view returns(bool) { return _preSalesFinished && !paused() && !_publicSalesFinished; } /** * * Returns whether or not preSales has finished * */ function preSalesFinished() public view returns(bool) { return _preSalesFinished; } /** * * Returns whether or not public Sales has finished * */ function publicSalesFinished() public view returns(bool) { return _publicSalesFinished; } /** * * Returns whether or not an address is in the presales list * */ function AddrInPresales(address _account) public view returns (bool){ return _inPresalesMode && !_preSalesFinished && hasRole(PRESALES_ROLE,_account) && (_preSalesMinted[_account]) < maxPresalesNFTAmount; } /** * * Returns whether or not an address is in the white list * */ function AddrInWhiteList(address _account) public view returns (bool){ return hasRole(WHITELIST_ROLE,_account) && (_whiteListMinted[_account]) < maxWhiteListNFTAmount; } /** * * Returns whether or not caller function is in the presales list * */ function AmIinPresales() external view returns (bool) { return AddrInPresales(msg.sender); } /** * * Returns max drop * */ function getMaxDrop() external view returns(uint256) { return maxDrop; } /** * * Returns tokenURI for the provider token id * */ function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { require(_exists(tokenId)); // dev: ERC721Metadata, URI query for nonexistent token string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(),".json")) : ""; } /** * * Payable mint during pre-sales * */ function preSalesMint(uint256 amount) public payable onlyRole(PRESALES_ROLE) { require(!(msg.sender.isContract())); // dev: The address is not an account require(totalSupply() + amount <= maxPresales); // dev: Pre-sales SOLD-OUT require(!_preSalesFinished || msg.sender == owner()); // dev: Pre-sales has already finished require(_inPresalesMode || msg.sender == owner()); // dev: Pre-sales has not started yet require(!paused() || msg.sender == owner()); // dev: Minting is paused require(msg.value == preSalesMintPrice*amount || msg.sender == owner()); // dev: Wrong price provided require(hasRole(PRESALES_ROLE, msg.sender) || msg.sender == owner()); // dev: Wallet not elligible require(amount <= maxPresalesNFTAmount); // dev: Cannot mint the specified amount in pre-sales require((_preSalesMinted[msg.sender] + amount) <= maxPresalesNFTAmount); // dev: Total pre-sales amount exceeded for wallet // Mint the amount of tokens! _coreMint(amount); // this was the last pre-sales minting based on the max presales allowed if(totalSupply() == maxPresales) { _preSalesFinished = true; _inPresalesMode = false; emit maxPreSalesReached(maxPresales); } // Keep track of wallet's pre-mint amount _preSalesMinted[msg.sender] += amount; } /** * To allow owners to reserve some collectibles at the begginning */ function initialMint(uint256 amount) external onlyOwner { require(msg.sender == owner()); // dev: not owner require(!(msg.sender.isContract())); // dev: The address is not an account require(!wlAllocated); // dev: initial amount already allocated require((wlAllocatedAmount + amount) <= maxWhiteListAmount); // dev: the initial amount is exceeded require((totalSupply() + amount) <= maxDrop); // dev: SOLD OUT! // Mint the amount! _coreMint(amount); wlAllocatedAmount += amount; if(wlAllocatedAmount == maxWhiteListAmount) { wlAllocated = true; emit maxWhiteListReached(maxWhiteListAmount); } } /** * * Not Payable mint * */ function whiteListMint(uint256 amount) public onlyRole(WHITELIST_ROLE) { require(!wlAllocated); // dev: initial amount already allocated require(!(msg.sender.isContract())); // dev: The address is not an account require((wlAllocatedAmount + amount) <= maxWhiteListAmount); // dev: the initial amount is exceeded require(hasRole(WHITELIST_ROLE, msg.sender) || msg.sender == owner()); // dev: Wallet not elligible require(totalSupply() + amount <= maxDrop); // dev: SOLD OUT! require((_whiteListMinted[msg.sender] + amount) <= maxWhiteListNFTAmount); // dev: Total amount exceeded for white-listed wallet // Mint the amount of tokens! _coreMint(amount); wlAllocatedAmount += amount; if(wlAllocatedAmount >= maxWhiteListAmount) { wlAllocated = true; emit maxWhiteListReached(maxWhiteListAmount); } // Keep track of wallet's white list amount _whiteListMinted[msg.sender] += amount; } /** * * Payable Public Sales mint version * */ function mint(uint256 amount) public payable { require(!(msg.sender.isContract())); // dev: The address is not an account require(_preSalesFinished || msg.sender == owner()); // dev: Pre-sales has not finished yet require(!paused() || msg.sender == owner()); // dev: Minting is paused require(msg.value == mintPrice*amount || msg.sender == owner()); // dev: Wrong price provided require(totalSupply() + amount <= maxDrop); // dev: SOLD OUT! require(amount <= maxSalesNFTAmount); // dev: Specified amount exceeds per-wallet maximum mint // Mint the amount! _coreMint(amount); // this was the last pre-sales minting based on the max presales allowed if(totalSupply() == maxDrop) { _publicSalesFinished = true; emit maxPublicSalesReached(maxDrop); } // Reserve in TH as per Roadmap _accumulateTH(); } /** ---------- ONLY OWNER CAN CALL EXTERNALLY ------------ */ /** * * Change baseURI * */ function setBaseURI(string memory baseURI) external onlyOwner { _baseTokenURI = baseURI; emit baseURIChanged(_baseTokenURI); } /** * * External function to allow to provide a list of addresses to be white listed * */ function addToWhiteList(address[] memory whiteListAddr) external onlyOwner { uint256 numAddrs = whiteListAddr.length; for(uint256 i=0;i<numAddrs;i++) { addToWhiteList(whiteListAddr[i]); } } /** * * External function to allow to provide a list of addresses to be white listed * fo presales * */ function addToPresalesList(address[] memory presalesAddr) external onlyOwner { require(!_preSalesFinished); // dev: Pre-sales period has already finished uint256 numAddrs = presalesAddr.length; for(uint256 i=0;i<numAddrs;i++) { addToPresalesList(presalesAddr[i]); } } /** ---------- ONLY OWNER CAN CALL, EVERYWHERE ------------ */ /** * * Allow to pause minting * */ function pause() public onlyOwner { _pause(); } /** * * Allow to unpause minting * */ function unpause() public onlyOwner { _unpause(); } /** * * Allow to enable or disable pre-sales * */ function preSalesOn() public onlyOwner { _inPresalesMode = true; _preSalesFinished = false; emit preSales(_inPresalesMode); } /** * * Stop presales * */ function preSalesOff() public onlyOwner { _inPresalesMode = false; emit preSales(_inPresalesMode); } /** * * Complete preSales * */ function preSalesComplete() public onlyOwner { _preSalesFinished = true; preSalesOff(); pause(); emit preSalesCompleted(); } /** ------- INTERNAL CALLS ONLY, SOME ONLY BY OWNER -------- */ /** * * Returns baseURI for tokens * */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * * Internal: adds the individual provided wallet to the white list list * */ function addToWhiteList(address whiteListAddr) internal onlyOwner { require(!whiteListAddr.isContract()); // dev: The address is not an account require(!hasRole(WHITELIST_ROLE, whiteListAddr)); // dev: Already in list grantRole(WHITELIST_ROLE,whiteListAddr); } /** * * Internal: adds the individual provided wallet to the presales list * */ function addToPresalesList(address presalesAddr) internal onlyOwner { require(!presalesAddr.isContract()); // dev: The address is not an account require(_presalesCounter.current() < maxPresales); // dev: Maximum number of presales reached require(!hasRole(PRESALES_ROLE, presalesAddr)); // dev: Already in list require(!_preSalesFinished); // dev: Pre-sales period has already finished grantRole(PRESALES_ROLE,presalesAddr); _presalesCounter.increment(); } /** * * Internal mint function * */ function _coreMint(uint256 amount) internal { uint256 tokenId; for(uint256 i = 0; i < amount; i++) { // Generate new tokenId _tokenIdCounter.increment(); tokenId = _tokenIdCounter.current(); // mint the tokenId for caller _safeMint(msg.sender, tokenId); } } /** ------- OVERRIDES NEEDED BY SOLIDITY -------- */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal whenNotPaused override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { require(maxDrop>0); // dev: cannot burn more maxDrop = maxDrop-1; super._burn(tokenId); } /** ------- VIRTUAL FUNCTIONS -------- */ function emitMintEvent(uint256 number) internal virtual; function _accumulateTH() internal virtual; /** ------- HELPER FUNCTIONS DURING UNIT TEST, ONLY BY OWNER -------- */ function setMaxDrop(uint256 _maxPresales,uint256 _maxDrop,uint256 _maxWhiteListAmount) public onlyOwner { require(_maxWhiteListAmount <= _maxDrop); // dev: max presales cannot be greater than maxDrop require((_maxWhiteListAmount + _maxPresales) <= _maxDrop); // dev: whitelist and presales sum more than maxdrop require(_maxDrop >= totalSupply()); // dev: cannot set maxDrop below already supply require(_maxPresales <= _maxDrop); // dev: max presales cannot be greater than maxDrop maxDrop = _maxDrop; maxPresales = _maxPresales; maxWhiteListAmount = _maxWhiteListAmount; _accumulateTH(); } function setMaxDrop(uint256 _maxDrop) public onlyOwner { require(_maxDrop >= totalSupply()); // dev: cannot set maxDrop below already supply maxDrop = _maxDrop; _accumulateTH(); } function setMaxSalesNFTAmount(uint256 _maxSalesNFTAmount) public onlyOwner { maxSalesNFTAmount = _maxSalesNFTAmount; } function setMaxWhiteListAmount(uint256 _maxWhiteListAmount) public onlyOwner { maxWhiteListAmount = _maxWhiteListAmount; } /** * Prizes related */ // To avoid reentrancy function withdrawPayments(address payable payee) public override nonReentrant whenNotPaused { super.withdrawPayments(payee); } function sendGiveAway(uint256 _giveAwayId, address[] memory _winners) external onlyOwner virtual whenNotPaused { } /** Semi-random function to allow selection of winner for giveaways*/ function rand(uint256 div) public view returns(uint256) { uint256 seed = uint256(keccak256(abi.encodePacked( block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)) + block.number ))); return (seed - ((seed / div) * div)); } } // File: Scissors.sol // // .,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,,,. .,,,, // ,,,, ,,, // ,,,, ((((( , , (( (( ,, // ,,, ((((/(((( ,,,,,,,, (((( ((( ,,, // ,,. (((( (((. ,,,, ,(((((( ,,, // ,,. (((( (((. ,,,,,, ,(((((( ,,, // ,,, ((((((((( .,,, ,,, (((( ,,, // ,,, ,,, // .,, @@@@@@@@@ @@@@@@@@@ @@@@@@@@ ,,, // ,,, @@ @@ @@ @@ @@ ,,, // ,,, @@ @ @@ @@ @@@ ,,, // ,,, @@@@@@@@@ @@@@@@@@@ @@@@@ ,,, // ,,, @@ @ @@ @@@ ,,, // ,,, @@ @@ @@ @@@@@@@@@ ,,,. // ,,, ,,,, // ,,,,. ,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,,,. // // /// @title Scissors Contract. /// Contract by RpsNft_Art /// Contract created by: (SHA-256) d735dfa8fa552fcb02c42894edebb4652d44697d1636b6125d2367caf2ade334 contract Scissors is RPSCollectible { // List of public ETH addresses of RPSNft_Art cofounders and other related participants address private NGOAddress = 0x633b7218644b83D57d90e7299039ebAb19698e9C; // UkraineDAO address private ScissorsSisterAddress = 0x92dd828AF04277f1ae6A4b7B25b5fFfc69f3A677; address private RockbiosaAddress = 0x521A4b1A8A968A232ca2BeCfF66713b209Bca2d7; address private PaperJamAddress = 0x57032e15279f520cb98365138533793dfA32d214; address private RoseLizardAddress = 0x502f9198E63D1EEa55C8Bd62e134d8c04CB66B73; address private SpockAddress = 0xBF2117339eD7A9039D9B996a61876150DDcc6b37; address private MarketingAddress = 0x09870346A435E6Eb14887742824BBC7dAd066776; address private FirstPrizeAddress = 0xD0f5C2aD5abA241A18D8E95e761982D911Ed1B20; address private DreamOnAddress = 0xFfFaBC56a346929f925ddF2dEEc86332CC1Ce437; // Token Ids that will determine the VIPs (using ownerof) uint256 [] private VIPTokens; bool private VIPTokensSet=false; // Events for NFT event CreateScissors(uint256 indexed id); event ReleaseTH(uint256 indexed _pct, uint256 _amount); event AmountWithdrawn(address _target, uint256 _amount); // Events for Prizes event FirstGiveAwayCharged(); event SecondGiveAwayCharged(address[]); event ThirdGiveAwayCharged(string _teamName,address[]); // Number of MAX_VIP_TOKENS uint256 public constant MAX_VIP_TOKENS = 20; // ETHs to acummulate in Treasure Hunt account uint256 public constant TH_POOL = 50000000000000000000; // 50 ETH uint256 public constant TH_FIRST = 5000000000000000000; // 5 ETH uint256 public constant TH_SECOND = 10000000000000000000; // 10 ETH uint256 public constant TH_THIRD = 15000000000000000000; // 15 ETH uint256 public constant TH_FOURTH = 20000000000000000000; // 20 ETH // PCT distributions uint256 public constant COFOUNDER_PCT = 16; // 16 PCT uint256 public constant FIVE_PCT = 5; // 5 PCT // Prizes uint256 public constant TH_PRIZE_PER_WALLET = 5000000000000000000; // 5 ETH uint256 public constant FIRST_PRIZE = 1; uint256 public constant SECOND_PRIZE = 2; uint256 public constant THIRD_PRIZE = 3; uint256 public constant FIRST_PRIZE_TOTAL_ETH_AMOUNT = 4000000000000000000; // 4 ETH uint256 public constant FIRST_PRIZE_FIRST_ETH_AMOUNT = 2500000000000000000; // 2.5 ETH uint256 public constant FIRST_PRIZE_SECOND_ETH_AMOUNT = 1000000000000000000; // 1 ETH uint256 public constant FIRST_PRIZE_THIRD_ETH_AMOUNT = 500000000000000000; // 0.5 ETH uint256 public constant SECOND_PRIZE_TOTAL_ETH_AMOUNT = 5000000000000000000; // 5 ETH uint256 public constant SECOND_PRIZE_PER_WALLET_ETH_AMOUNT = 250000000000000000; // 0.25 ETH uint256 public constant TH_SECOND_PRIZE_MAX_WINNERS = 20; uint256 public constant TH_THIRD_PRIZE_MAX_WINNERS = 10; // track if prizes have been released bool public first_prize_released = false; bool public second_prize_released = false; bool public third_prize_released = false; // Store the TH Secret - Winner will provide the team 50 ETH uint256 private accumulatedTHPrize = 0; bytes32 private th_secret = 0x0; bool private th_secret_set = false; // Usings using Address for address; // Keep track of percentages achieved and accumulation for TH accomplished bool _allocatedTH_25 = false; bool _allocatedTH_50 = false; bool _allocatedTH_75 = false; bool _allocatedTH_100 = false; // table for 2nd prize winners address[] public second_prize_winners; // mapping to register potential 3rd prize winners. Each array of tokenids must be // max of TH_THIRD_PRIZE_MAX_WINNERS. Address index is who represents a given group and who calls // payable function to register group mapping(string => address[]) public third_prize_players; // keep track of team where addresses are registered against mapping(address => string) public registered_th_addresses; string public th_team_winner = ''; /** * RPS = Rock Paper Scissors * MWSA = Mintable Scissors Art */ constructor() RPSCollectible("RPS Scissors", "MSA") { require(!(msg.sender.isContract())); // dev: The address is not an account // So far, to get the metadata from web but soon replace from // pre-loaded IPFS //_baseTokenURI = "ipfs://QmT9Qb3tQfvKC1bnXPqGo5UnBgdU2WK4kq5SzVo4zPcWig/"; maxDrop = 10000; VIPTokensSet = false; preSalesMintPrice = 55000000000000000; // 0.055 ETH mintPrice = 70000000000000000; // 0.070 ETH maxPresales = 3500; // 1750 (250+1500) Max accts, each 2 max so max 3500 NFTs maxPresalesNFTAmount = 2; // Max number of NFTs per wallet to mint during pre-sales maxWhiteListNFTAmount = 2; // Max number of NFTs per wallet to mint per whitelisted account maxSalesNFTAmount = 25; // Max number of NFTs per wallet to mint during sales (no other control per account) maxWhiteListAmount = 150; // Max allowance for whitelisted tokens (including contract owners) accumulatedTHPrize = 0; // to keep track of accumulated TH balance as per roadmap th_secret_set = false; // to be set when secret is resolved } /** ---- ANYONE CAN CALL, SOME EXTERNAL ONLY ---- */ /*** * * Maximum balance that can be withdrawn to secure future prices * */ function maxBalanceToWithdraw() public view returns(uint256) { uint256 balance = address(this).balance; int256 max_balance = int256(balance); // Do not transfer TH pool and prizes part if(!_allocatedTH_25) { // 25% has not been reached so do not allow to withdraw that part max_balance = max_balance - int256 (TH_FIRST) - int256(FIRST_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_50) { // 50% has not been reached so do not allow to withdraw the TH part (5+10) and 1st prize max_balance = max_balance - int256 (accumulatedTHPrize + TH_SECOND) - int256(FIRST_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_75) { // 75% has not been reached so do not allow to withdraw the TH part (5+10+15) and 2nd prize max_balance = max_balance - int256 (accumulatedTHPrize + TH_THIRD) - int256(SECOND_PRIZE_TOTAL_ETH_AMOUNT); } else if(!_allocatedTH_100 || !third_prize_released) { // 100% has not been reached, do not allow to release the TH_POOL // OR // 100% reached BUT TH_POOL has not been released yet, do not allow to withdraw it max_balance = max_balance - int256 (TH_POOL); } // if max_balance is positive after ensuring Treasure Hunt // payments, then we can distribute if(max_balance > 0) { balance = uint256(max_balance); } else { balance = 0; } return balance; } /** * * Charging the contract for test purposes: it is just fine by calling this empty payable method * */ function chargeContract() external payable { } /** ---------- ONLY OWNER CAN CALL ------------ */ /** * * Allow to withdraw the accumulated balance among founders, always prioritizing * Treasure Hunt payments * */ function withdraw() external onlyOwner { require(VIPTokensSet); // dev: VIP tokens unknown // Keep amount for prizes uint256 balance = maxBalanceToWithdraw(); require(balance > 0); // dev: nothing to withdraw after securing prizes // Calc stakes from max to withdraw // Solidity missing floats -> first mul then div uint256 cofounder_stk = (balance*COFOUNDER_PCT)/100; // Co-founders uint256 VIP_stk = cofounder_stk / VIPTokens.length; // VIPs participation // Early investor pct, NGO steak, For future marketing campaings, Participation of Dream On uint256 five_pct = (balance*FIVE_PCT)/100; // Transfer for founders transferFounders(cofounder_stk); // Transfer to VIPs transferVIPs(VIP_stk); // Transfer to believer payable(SpockAddress).transfer(five_pct); emit AmountWithdrawn(SpockAddress, five_pct); // Transfer to dream_on payable(DreamOnAddress).transfer(five_pct); emit AmountWithdrawn(DreamOnAddress, five_pct); // Transfer to NGO payable(NGOAddress).transfer(five_pct); emit AmountWithdrawn(NGOAddress, five_pct); // Pool for new marketing investment payable(MarketingAddress).transfer(five_pct); emit AmountWithdrawn(MarketingAddress, five_pct); } /** * * Sets the tokens for cofounding benefits * */ function setVIPTokens(uint256 [] memory _tokens) external onlyOwner { uint256 len = _tokens.length; require(len > 0); // dev: no tokens of VIPs provided require(len <= MAX_VIP_TOKENS); // dev: max number of VIPs is 20 VIPTokens = new uint256[](_tokens.length); for(uint256 i=0;i < len;i++) { VIPTokens[i] = _tokens[i]; } VIPTokensSet = true; } /** * * Allow changing addresses for cofounders * */ function setFounderAddresses(address _ss, address _rb, address _pj, address _rl,address _sp, address _ngo, address _ds, address _do) external onlyOwner { ScissorsSisterAddress = _ss; RockbiosaAddress = _rb; PaperJamAddress = _pj; RoseLizardAddress = _rl; SpockAddress = _sp; NGOAddress = _ngo; MarketingAddress = _ds; DreamOnAddress = _do; } /** * Set First and Second Prize addresses */ function setPrizesAccounts(address _first) external onlyOwner { require(!_first.isContract()); // dev: the address is not an account FirstPrizeAddress = _first; } /** ---------- INTERNAL FUNCTIONS, SOME ONLY OWNER ------------ */ /** * * Specific event created when Scissor mints * */ function emitMintEvent(uint256 collectibleId) internal override { emit CreateScissors(collectibleId); } /** * * Function that is called per every mint and allocates treasure hunt * as per roadmap * * It also accumulates for 1st and 2nd prize * */ function _accumulateTH() internal override { // Everything already allocated in TH if(_allocatedTH_100) return; // Transfer amount of ETHs as per roadmap to TreasureHunt account (25%) if(!_allocatedTH_25 && pctReached(25) && address(this).balance>TH_FIRST) { _allocatedTH_25 = true; accumulatedTHPrize += TH_FIRST; emit ReleaseTH(25, TH_FIRST); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (50%) if(!_allocatedTH_50 && pctReached(50) && address(this).balance>(TH_SECOND + FIRST_PRIZE_TOTAL_ETH_AMOUNT)) { payable(FirstPrizeAddress).transfer(FIRST_PRIZE_TOTAL_ETH_AMOUNT); // Transfer 1st prize _allocatedTH_50 = true; accumulatedTHPrize += TH_SECOND; emit ReleaseTH(50, TH_SECOND); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (75%) if(!_allocatedTH_75 && pctReached(75) && address(this).balance>(TH_THIRD + SECOND_PRIZE_TOTAL_ETH_AMOUNT)) { // send 2nd GiveAway to random owners _secondGiveAway(); _allocatedTH_75 = true; // Accumulate for TH accumulatedTHPrize += TH_THIRD; emit ReleaseTH(75, TH_THIRD); } // Transfer amount of ETHs as per roadmap to TreasureHunt account (100%) if(!_allocatedTH_100 && pctReached(100) && address(this).balance>TH_FOURTH) { _allocatedTH_100 = true; accumulatedTHPrize += TH_FOURTH; emit ReleaseTH(100,TH_FOURTH); } } /** * * Transfer for Founders * */ function transferFounders(uint256 _amount) internal onlyOwner { // divide remainder among founders payable(RockbiosaAddress).transfer(_amount); emit AmountWithdrawn(RockbiosaAddress, _amount); payable(PaperJamAddress).transfer(_amount); emit AmountWithdrawn(PaperJamAddress, _amount); payable(ScissorsSisterAddress).transfer(_amount); emit AmountWithdrawn(ScissorsSisterAddress, _amount); payable(RoseLizardAddress).transfer(_amount); emit AmountWithdrawn(RoseLizardAddress, _amount); } /** * * Transfer for VIPs * */ function transferVIPs(uint256 _amount) internal onlyOwner { require(VIPTokensSet); // dev: VIP tokens unknown // Pull payments of a 10th of the total for VIP // each VIP gets a pullpayment with proportional amount for(uint256 i=0;i < VIPTokens.length;i++) { // get the owner of the item to get payment address _ccfAddr = ownerOf(VIPTokens[i]); _asyncTransfer(_ccfAddr, _amount); emit AmountWithdrawn(_ccfAddr, _amount); } } /** * Prizes related functions */ /** * Returns whether a given percentage has been reached or not */ function pctReached(uint256 pct) public view returns(bool) { bool ret = false; if(pct == 25) { ret = (totalSupply()>=(maxDrop / 4)); } else if(pct == 50) { ret=(totalSupply()>=(maxDrop / 2)); } else if(pct == 75) { ret=(totalSupply()>=((3*maxDrop) / 4)); } else if(pct == 100) { ret=(totalSupply()>=(maxDrop)); } return(ret); } /** * Sets the TH secret up */ function setSecret(bytes32 _secret) external onlyOwner { th_secret = _secret; th_secret_set = true; } function reservedTHPrize() external view returns(uint256) { return accumulatedTHPrize; } function sendGiveAway(uint256 _giveAwayId, address[] memory _winners) public override onlyOwner { uint256[3] memory _prizes = [FIRST_PRIZE_FIRST_ETH_AMOUNT, // 2.5 ETH FIRST_PRIZE_SECOND_ETH_AMOUNT, // 1 ETH FIRST_PRIZE_THIRD_ETH_AMOUNT]; //0.5 ETH if(_giveAwayId == FIRST_PRIZE) { // send first GiveAway _firstGiveAway(_winners,_prizes); } } // Drop 1, once we have achieved 50% of the sales during first drop, // the 3 community members from community members list, who have brought more new members // to the community, will be rewarded with 2.5 ETH the first 1, 1 ETH the second, and 0.5 ETH the third. // Total: 4 ETH function _firstGiveAway(address[] memory _winners,uint256[3] memory _prizes) private onlyOwner { require(pctReached(50)); // dev: 50% not achieved yet require(!first_prize_released); // dev: 1st prize already released require(_winners.length <= 3); // dev: winners array greater than 3 require(address(this).balance >= FIRST_PRIZE_TOTAL_ETH_AMOUNT); // dev: not enough balance in contract for(uint256 i=0;i<_winners.length;i++) { if(_winners[i] != address(0x0)) { _asyncTransfer(_winners[i],_prizes[i]); // 2.5 ETH, 1 ETH, 0.5 ETH // Flag prize as released first_prize_released = true; emit FirstGiveAwayCharged(); } } } // Drop 1, after 75% minting 5 ETH are transferred to 20 random scissors owners (pull payment, 0.5 ETH each) function _secondGiveAway() internal { require(!second_prize_released); // dev: 2nd prize already released require(pctReached(75)); // dev: 75% not achieved yet require(address(this).balance >= SECOND_PRIZE_PER_WALLET_ETH_AMOUNT); // dev: not enough balance in contract uint256 top_75_pct = (3*maxDrop)/4; // calc the 75% of the maxDrop second_prize_winners = new address[](TH_SECOND_PRIZE_MAX_WINNERS); // Get 20 random tokenId numbers from 0...(maxDrop*3)/4 uint256 div = top_75_pct / TH_SECOND_PRIZE_MAX_WINNERS; uint256 seed = rand(div) + 1; // Add payment in escrow contract for(uint256 i = 0; i < TH_SECOND_PRIZE_MAX_WINNERS; i++) { second_prize_winners[i] = ownerOf(seed); _asyncTransfer(second_prize_winners[i],SECOND_PRIZE_PER_WALLET_ETH_AMOUNT); seed = seed + div; } second_prize_released = true; emit SecondGiveAwayCharged(second_prize_winners); } /** * Returns the addresses of token owners (max of TH_THIRD_PRIZE_MAX_WINNERS) * internally called by owner of the tokens */ function getAddressesFromTokens(uint256 [] memory _tokens) internal returns (address [] memory) { address [] memory ret = new address[](_tokens.length); for(uint256 i=0;i<_tokens.length;i++) { address _tokenOwner = ownerOf(_tokens[i]); require(msg.sender == _tokenOwner); // dev: caller is not the owner ret[i] = _tokenOwner; } return ret; } /** * Helper function to determine if one of the addresses is already registered in a team */ function addressesNotRegisteredInTeamYet(address[] memory _addrs) internal returns (bool) { bool ret = true; for(uint256 i=0;i<_addrs.length;i++) { if(bytes(registered_th_addresses[_addrs[i]]).length != 0) { // Address already registered in a team ret = false; break; } } return ret; } function addAddrToTeam(address _addr, string memory _teamName, uint256 _amount) internal returns(uint256) { registered_th_addresses[_addr] = _teamName; return _amount + 1; } /** * Registers a new Team for TH prize * - caller of this function will provide list of tokens he/she owns to include his address * in this team and to create the team * - caller of this function is free of charge (only gas) * - Returns: number of shares in the team (max of TH_THIRD_PRIZE_MAX_WINNERS-1) */ function registerTHTeam(string memory _teamName, uint256[] memory _tokensTeam) external returns(uint256) { require(_tokensTeam.length < TH_THIRD_PRIZE_MAX_WINNERS); // dev: tokens list size exceed maximum to create list require(third_prize_players[_teamName].length == 0); // dev: team name already taken uint256 ret = 0; // Get addresses for tokens provided to create this team address [] memory _addrs = getAddressesFromTokens(_tokensTeam); // Caller must but owner of the tokens or exception // if some address already registered in another team, exception require(addressesNotRegisteredInTeamYet(_addrs)); // Flag address as registered under _teamName so it cannot be registered in another team for(uint256 i=0;i<_addrs.length;i++) { ret = addAddrToTeam(_addrs[i],_teamName,ret); } // Finally, we can register the team third_prize_players[_teamName] = _addrs; return ret; } /** * Caller calls this function if he/she wants to join a TH team */ function joinTHTeam(string memory _teamName, uint256[] memory _tokensTeam) external returns(uint256) { require(third_prize_players[_teamName].length != 0); // dev: team name does not exist require(third_prize_players[_teamName].length != TH_THIRD_PRIZE_MAX_WINNERS); // dev: team full uint256 ret = 0; // Get addresses for tokens provided to create this team // Caller must but owner of the tokens or exception address [] memory _addrs = getAddressesFromTokens(_tokensTeam); // if some address already registered in another team, exception require(addressesNotRegisteredInTeamYet(_addrs)); // dev: caller not in a team yet for(uint256 i=0;i<_addrs.length;i++) { // if there still some room left, add new joiner if(third_prize_players[_teamName].length < TH_THIRD_PRIZE_MAX_WINNERS) { // Finally, we can register the team third_prize_players[_teamName].push(_addrs[i]); ret = addAddrToTeam(_addrs[i],_teamName,ret); } } return ret; } /** * Function that registered users need to call to provide decrypted message _plaintext * If text matches the encrypted message, TH prize will be distributed to owners of scissors * registered in the team from the caller attending to their participation * */ function decryptForTHPrize(string memory _plaintext) external returns(bool) { require(th_secret_set); // dev: secret not set require(pctReached(100)); // dev: 100% not achieved yet require(!third_prize_released); // dev: 3rd prize already released require(accumulatedTHPrize == TH_POOL); // dev: not enough balance in contract require(address(this).balance >= TH_POOL); // dev: not enough balance in contract require(bytes(registered_th_addresses[msg.sender]).length != 0); // dev: caller not registered in any team if(keccak256(abi.encodePacked(_plaintext)) == th_secret) { // Secret message found, release prize to winners in team // Get the team name th_team_winner = registered_th_addresses[msg.sender]; // Access the addresses list address [] memory _winnersAddrs = third_prize_players[th_team_winner]; // Congrats winners _charge3rdGiveAway(th_team_winner,_winnersAddrs); return true; } else { revert("RPS - Wrong, keep trying."); } return false; } /** * Returns addresses of TH winners */ function getTHWinnerAddrs() external view returns(address[] memory) { require(third_prize_released); // dev: TH prize not relased yet return third_prize_players[th_team_winner]; } /** * Returns TH winner team name */ function getTHTeamName() external view returns(string memory) { require(third_prize_released); // dev: TH prize not relased yet return th_team_winner; } // The 50 ETH accumulated in the treasure account will be equally distributed among the winner group // and the corresponding will be made available to them through pullpayment. // Example if the group was formed by 10 people with 10 corresponding accounts, // 5 ETH will be made available to them through pull payment. function _charge3rdGiveAway(string memory _teamName, address[] memory _winners) internal { // We transfer amount in the contract and from the contract to payees // using pullpayment method for(uint256 i=0;i<_winners.length;i++) { _asyncTransfer(_winners[i],TH_PRIZE_PER_WALLET); // 5 ETH per wallet accumulatedTHPrize -= TH_PRIZE_PER_WALLET; } third_prize_released = true; emit ThirdGiveAwayCharged(_teamName,_winners); } /** * We will transfer any accumulated prize not provided to NGO account */ function sendRemainderToNGO() external onlyOwner { require(third_prize_released && accumulatedTHPrize > 0); // dev: prizes not released yet or no remaining // All prizes have been released, potential remainder to be sent to NGO uint256 amount = accumulatedTHPrize; payable(NGOAddress).transfer(amount); emit AmountWithdrawn(NGOAddress, amount); } }
Complete preSales/
function preSalesComplete() public onlyOwner { _preSalesFinished = true; preSalesOff(); pause(); emit preSalesCompleted(); }
586,390
// File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/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/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. * * [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"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/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. * * 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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/711/dependencies/IWETH.sol pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // File: contracts/711/dependencies/uniswapv2/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 migrator() 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; function setMigrator(address) external; } // File: contracts/711/dependencies/uniswapv2/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/711/dependencies/uniswapv2/interfaces/IUniswapV2Router02.sol pragma solidity >=0.5.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: contracts/711/dependencies/IStakingRewards.sol pragma solidity ^0.5.0; interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function rewardsToken() external view returns (IERC20); function stakingToken() external view returns (IERC20); function rewardRate() external view returns (uint256); // Mutative function stake(uint256 amount) external; function stakeFor(address to, uint256 amount) external; function withdraw() external; function getReward() external; function exit() external; function notifyRewardAmount(uint256 reward) external; } // File: contracts/711/dependencies/IAgentRegistry.sol pragma solidity >=0.5.0; interface IAgentRegistry { function agents() external returns (uint256); function register(string calldata _nameString) external payable; function getAgentAddressById(uint256 _agentId) external view returns (address payable); function getAgentAddressByName(bytes32 _agentName) external view returns (address payable); function isAgent(address _agent) external view returns (bool); } // File: contracts/711/ADDRESSBOOK.sol pragma solidity ^0.5.0; contract ADDRESSBOOK { address constant public FEE_APPROVER = 0x6C70d504932AA318f8070De13F3c4Ab69A87953f; address payable constant public VAULT = 0xB1ff949285107B7b967c0d05886F2513488D0042; address constant public REWARDS_DISTRIBUTOR = 0xB3c39777142320F7C5329bF87287A707C77266e3; address constant public STAKING_CONTRACT = 0x29d44e1726e4368e5A7Abf4fbC481a874AebCf00; address constant public ZAP = 0x0797778B9110D03FF64fF25192e2a980Bf4523b8; address constant public TOKEN_ADDRESS_711 = 0x9d4709e7C38e7857636c342a37547E191125E028; address constant public AGENT_REGISTRY = 0x35C9Dbd51D926838cAc8eB33ebDbEA5e2930b247; address constant public UNISWAP_V2_PAIR_711_WETH = 0xF295b0fa1A89c8a06109fB2D2c860a96Fb39dca5; } // File: contracts/711/ZapIn_711_V2.sol // ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗ // ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║ // ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║ // ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║ // ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║ // ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝ // Copyright (C) 2020 zapper, nodar, suhail, seb, sumit, apoorv // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // SPDX-License-Identifier: GPLv2 pragma solidity ^0.5.16; // import "@uniswap/lib/contracts/libraries/Babylonian.sol"; library Babylonian { 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; } // else z = 0 } } contract ZapIn_711_V2 is ReentrancyGuard, Ownable, ADDRESSBOOK { using SafeMath for uint256; using Address for address; using SafeERC20 for IERC20; event AmountToAgent(address indexed from, address indexed agent, uint256 ethAmount); event AmountToVault(address indexed from, uint256 ethAmount); event AmountToInvest(address indexed from, uint256 ethAmount, uint256 lpBought); mapping (address => uint256) public referralRewards; bool public stopped = false; uint16 public goodwill; address payable public vault; address public stakingContract; IAgentRegistry public agentRegistry; IUniswapV2Router02 private constant uniswapRouter = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory private constant UniSwapV2FactoryAddress = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); uint256 private constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; address private constant wethTokenAddress = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address private constant ethTokenAddress = address(0); // only accepts ETH constructor() public { goodwill = 1000; vault = VAULT; stakingContract = STAKING_CONTRACT; agentRegistry = IAgentRegistry(AGENT_REGISTRY); } // circuit breaker modifiers modifier stopInEmergency { if (stopped) { revert("Temporarily Paused"); } else { _; } } // Zap in with referral id function ZapInWithId( address _staker, uint256 _minPoolTokens, uint256 _agentId ) public payable stopInEmergency returns (uint256) { //query agent address payable _agent = agentRegistry.getAgentAddressById(_agentId); ZapIn(_staker, _minPoolTokens, _agent); } // Zap in with referral name function ZapInWithName( address _staker, uint256 _minPoolTokens, bytes32 _agentName ) public payable stopInEmergency returns (uint256) { //query agent address payable _agent = agentRegistry.getAgentAddressByName(_agentName); ZapIn(_staker, _minPoolTokens, _agent); } /** @notice This function is used to single sided add liquidity to Uniswap V2 ETH/7-11 pair and stake @param _minPoolTokens Reverts if less tokens received than this @return Amount of stake amount */ function ZapIn( address _staker, uint256 _minPoolTokens, address payable _agent ) public payable nonReentrant stopInEmergency returns (uint256) { require(msg.value > 0, "Error: ETH not sent"); if(msg.sender == _agent || !(agentRegistry.isAgent(_agent))){ _agent = address(0); } // Default uint256 toVault = msg.value.mul(goodwill).div(10000); // 10% to vault uint256 toInvest = msg.value.sub(toVault); // 90% to swap // And if it is referred by an agent if(_agent != address(0)){ toVault = msg.value.mul(500).div(10000); // 5% to vault toInvest = msg.value.mul(9250).div(10000); // 92.5% to swap uint256 toAgent = msg.value.sub(toVault).sub(toInvest); // 2.5% to agent // Transfer to agnet _agent.transfer(toAgent); referralRewards[_agent] = referralRewards[_agent].add(toAgent); emit AmountToAgent(msg.sender, _agent, toAgent); } // Transfer to vault vault.transfer(toVault); emit AmountToVault(msg.sender, toVault); // Single sided add liquidity uint256 LPBought = _performZapIn( _staker, ethTokenAddress, TOKEN_ADDRESS_711, wethTokenAddress, toInvest ); emit AmountToInvest(msg.sender, toInvest, LPBought); require(LPBought >= _minPoolTokens, "ERR: High Slippage"); // Stake LP token IERC20(UNISWAP_V2_PAIR_711_WETH).safeApprove(stakingContract, LPBought); IStakingRewards(stakingContract).stakeFor(_staker, LPBought); return LPBought; } function _performZapIn( address _toWhomToIssue, address _FromTokenContractAddress, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 _amount ) internal returns (uint256) { address intermediate = _getIntermediate( _FromTokenContractAddress, _amount, _ToUnipoolToken0, _ToUnipoolToken1 ); // swap to intermediate uint256 interAmt = _token2Token( _FromTokenContractAddress, intermediate, _amount ); // divide to swap in amounts uint256 token0Bought; uint256 token1Bought; IUniswapV2Pair pair = IUniswapV2Pair( UniSwapV2FactoryAddress.getPair(_ToUnipoolToken0, _ToUnipoolToken1) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); if (intermediate == _ToUnipoolToken0) { uint256 amountToSwap = calculateSwapInAmount(res0, interAmt); //if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token1Bought = _token2Token( intermediate, _ToUnipoolToken1, amountToSwap ); token0Bought = interAmt.sub(amountToSwap); } else { uint256 amountToSwap = calculateSwapInAmount(res1, interAmt); //if no reserve or a new pair is created if (amountToSwap <= 0) amountToSwap = interAmt.div(2); token0Bought = _token2Token( intermediate, _ToUnipoolToken0, amountToSwap ); token1Bought = interAmt.sub(amountToSwap); } return _uniDeposit( _toWhomToIssue, _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought ); } function _uniDeposit( address _toWhomToIssue, address _ToUnipoolToken0, address _ToUnipoolToken1, uint256 token0Bought, uint256 token1Bought ) internal returns (uint256) { IERC20(_ToUnipoolToken0).safeIncreaseAllowance( address(uniswapRouter), token0Bought ); IERC20(_ToUnipoolToken1).safeIncreaseAllowance( address(uniswapRouter), token1Bought ); (uint256 amountA, uint256 amountB, uint256 LP) = uniswapRouter .addLiquidity( _ToUnipoolToken0, _ToUnipoolToken1, token0Bought, token1Bought, 1, 1, address(this), deadline ); //Returning Residue in token0, if any. if (token0Bought.sub(amountA) > 0) { IERC20(_ToUnipoolToken0).safeTransfer( _toWhomToIssue, token0Bought.sub(amountA) ); } //Returning Residue in token1, if any if (token1Bought.sub(amountB) > 0) { IERC20(_ToUnipoolToken1).safeTransfer( _toWhomToIssue, token1Bought.sub(amountB) ); } return LP; } function _getIntermediate( address _FromTokenContractAddress, uint256 _amount, address _ToUnipoolToken0, address _ToUnipoolToken1 ) internal view returns (address) { // set from to weth for eth input if (_FromTokenContractAddress == address(0)) { _FromTokenContractAddress = wethTokenAddress; } if (_FromTokenContractAddress == _ToUnipoolToken0) { return _ToUnipoolToken0; } else if (_FromTokenContractAddress == _ToUnipoolToken1) { return _ToUnipoolToken1; } else { IUniswapV2Pair pair = IUniswapV2Pair( UniSwapV2FactoryAddress.getPair( _ToUnipoolToken0, _ToUnipoolToken1 ) ); (uint256 res0, uint256 res1, ) = pair.getReserves(); uint256 ratio; bool isToken0Numerator; if (res0 >= res1) { ratio = res0 / res1; isToken0Numerator = true; } else { ratio = res1 / res0; } //find outputs on swap uint256 output0 = _calculateSwapOutput( _FromTokenContractAddress, _amount, _ToUnipoolToken0 ); uint256 output1 = _calculateSwapOutput( _FromTokenContractAddress, _amount, _ToUnipoolToken1 ); if (isToken0Numerator) { if (output1 * ratio >= output0) return _ToUnipoolToken1; else return _ToUnipoolToken0; } else { if (output0 * ratio >= output1) return _ToUnipoolToken0; else return _ToUnipoolToken1; } } } function _calculateSwapOutput( address _from, uint256 _amt, address _to ) internal view returns (uint256) { // check output via tokenA -> tokenB address pairA = UniSwapV2FactoryAddress.getPair(_from, _to); uint256 amtA; if (pairA != address(0)) { address[] memory pathA = new address[](2); pathA[0] = _from; pathA[1] = _to; amtA = uniswapRouter.getAmountsOut(_amt, pathA)[1]; } uint256 amtB; // check output via tokenA -> weth -> tokenB if ((_from != wethTokenAddress) && _to != wethTokenAddress) { address[] memory pathB = new address[](3); pathB[0] = _from; pathB[1] = wethTokenAddress; pathB[2] = _to; amtB = uniswapRouter.getAmountsOut(_amt, pathB)[2]; } if (amtA >= amtB) { return amtA; } else { return amtB; } } function calculateSwapInAmount(uint256 reserveIn, uint256 userIn) public pure returns (uint256) { return Babylonian .sqrt( reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009)) ) .sub(reserveIn.mul(1997)) / 1994; } /** @notice This function is used to swap ETH/ERC20 <> ETH/ERC20 @param _FromTokenContractAddress The token address to swap from. (0x00 for ETH) @param _ToTokenContractAddress The token address to swap to. (0x00 for ETH) @param tokens2Trade The amount of tokens to swap @return tokenBought The quantity of tokens bought */ function _token2Token( address _FromTokenContractAddress, address _ToTokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 tokenBought) { if (_FromTokenContractAddress == _ToTokenContractAddress) { return tokens2Trade; } if (_FromTokenContractAddress == address(0)) { if (_ToTokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).deposit.value(tokens2Trade)(); return tokens2Trade; } address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactETHForTokens.value( tokens2Trade )(1, path, address(this), deadline)[path.length - 1]; } else if (_ToTokenContractAddress == address(0)) { if (_FromTokenContractAddress == wethTokenAddress) { IWETH(wethTokenAddress).withdraw(tokens2Trade); return tokens2Trade; } IERC20(_FromTokenContractAddress).safeIncreaseAllowance( address(uniswapRouter), tokens2Trade ); address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForETH( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } else { IERC20(_FromTokenContractAddress).safeIncreaseAllowance( address(uniswapRouter), tokens2Trade ); if (_FromTokenContractAddress != wethTokenAddress) { if (_ToTokenContractAddress != wethTokenAddress) { // check output via tokenA -> tokenB address pairA = UniSwapV2FactoryAddress.getPair( _FromTokenContractAddress, _ToTokenContractAddress ); address[] memory pathA = new address[](2); pathA[0] = _FromTokenContractAddress; pathA[1] = _ToTokenContractAddress; uint256 amtA; if (pairA != address(0)) { amtA = uniswapRouter.getAmountsOut( tokens2Trade, pathA )[1]; } // check output via tokenA -> weth -> tokenB address[] memory pathB = new address[](3); pathB[0] = _FromTokenContractAddress; pathB[1] = wethTokenAddress; pathB[2] = _ToTokenContractAddress; uint256 amtB = uniswapRouter.getAmountsOut( tokens2Trade, pathB )[2]; if (amtA >= amtB) { tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathA, address(this), deadline )[pathA.length - 1]; } else { tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, pathB, address(this), deadline )[pathB.length - 1]; } } else { address[] memory path = new address[](2); path[0] = _FromTokenContractAddress; path[1] = wethTokenAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } } else { address[] memory path = new address[](2); path[0] = wethTokenAddress; path[1] = _ToTokenContractAddress; tokenBought = uniswapRouter.swapExactTokensForTokens( tokens2Trade, 1, path, address(this), deadline )[path.length - 1]; } } require(tokenBought > 0, "Error Swapping Tokens"); } /** @notice This function is used to calculate and transfer goodwill @param _tokenContractAddress Token in which goodwill is deducted @param tokens2Trade The total amount of tokens to be zapped in @return The quantity of goodwill deducted */ function _transferGoodwill( address _tokenContractAddress, uint256 tokens2Trade ) internal returns (uint256 goodwillPortion) { goodwillPortion = SafeMath.div( SafeMath.mul(tokens2Trade, goodwill), 10000 ); if (goodwillPortion == 0) { return 0; } IERC20(_tokenContractAddress).safeTransfer( vault, goodwillPortion ); } function set_new_goodwill(uint16 _new_goodwill) public onlyOwner { require( _new_goodwill >= 0 && _new_goodwill < 10000, "GoodWill Value not allowed" ); goodwill = _new_goodwill; } function inCaseTokengetsStuck(IERC20 _TokenAddress) public onlyOwner { uint256 qty = _TokenAddress.balanceOf(address(this)); _TokenAddress.safeTransfer(owner(), qty); } // - to Pause the contract function toggleContractActive() public onlyOwner { stopped = !stopped; } // - to withdraw any ETH balance sitting in the contract function withdraw() public onlyOwner { uint256 contractBalance = address(this).balance; address payable _to = owner().toPayable(); _to.transfer(contractBalance); } function() external payable { require(msg.sender != tx.origin, "Do not send ETH directly"); } }
Zap in with referral idquery agent
function ZapInWithId( address _staker, uint256 _minPoolTokens, uint256 _agentId ) public payable stopInEmergency returns (uint256) { address payable _agent = agentRegistry.getAgentAddressById(_agentId); ZapIn(_staker, _minPoolTokens, _agent); }
7,757,603
pragma solidity ^0.4.18; import './FuturesContract.sol'; import './oraclizeAPI.sol'; contract MarketPlace is usingOraclize { // Enum definitions enum UserLoginStatus { Online, Offline, Archieved } // Unscoped variables string public binanceBaseAPI = "https://api.binance.com/api/v3/ticker/price?symbol="; string[] public availablePairings = [ 'ETHEOS', 'ETHTRX', 'ETHOMG', 'ETHQTM' ]; uint256 constant timeStampInterval = 3*3600; uint256 public userOnlineCount; address owner; // Struct definitions struct User { bool exist; // For existance validation string name; UserLoginStatus status; // User online status uint256[] futuresContractID; // Stores list of signed contracts bytes32 passwordHash; } address[] userAddresses; uint256[] unsignedFuturesContactIds; // Mapping data struct mapping(address => User) users; mapping(uint256 => FuturesContract) signedFuturesContracts; mapping(uint256 => FuturesContract) unsignedFuturesContracts; // Event Logs // Admin Management Function Modifiers modifier onlyOwner() { require(msg.sender == owner);_; } // User Management Function Modifiers modifier userExist() { require(users[msg.sender].exist);_; } modifier notUserExist() { require(!users[msg.sender].exist);_; } modifier userIsOnline() { require(users[msg.sender].status == UserLoginStatus.Online);_; } // Contructor function MarketPlace() public { owner = msg.sender; } function signContractOf(address _seller, address _contractAddress) public payable userExist userIsOnline { // Sign contract from another User require(users[_seller].exist); User seller = users[_seller]; FuturesContract sellerContract = FuturesContract.at(_contractAddress); sellerContract.signContract(msg.sender); } function createContract(uint256 _expiryDate, uint256 _bettingPairs, uint256 _bettingPrice, string _position) public payable userExist userIsOnline { // User create new unsigned contract User currentUser = users[msg.sender]; string memory bettingAPI = strConcat(binanceBaseAPI, _bettingPairs); FuturesContract newContract = (new FuturesContract).value(msg.sender)( msg.sender, _expiryDate, _bettingPairs, _bettingPrice, _position, bettingAPI ); currentUser.futuresContractID.push(newContract.address); } // Admin Update Functions function updatePairings(string _newPairing) public onlyOwner { // Update Existing Pairing with ticker availablePairings.push(_newPairing); } // User Account Management Function function registerUser(string _name, string _password) public notUserExist { // Params Validation require(bytes(_name).length > 3); require(bytes(_password).length > 3); // Register new user to Contract users[msg.sender] = User({ exist: true, name: _name, status: UserLoginStatus.Offline, futuresContractID: new uint256[](0), passwordHash: keccak256(_password, _name) }); } function loginUser(string _name, string _password) public userExist { // Authenticate and set user login status to online require(authenticate(msg.sender, _name, _password)); users[msg.sender].status = UserLoginStatus.Online; userOnlineCount++; } function logoutUser() public userExist { // Authenticate and set user login status to offline User storage currentUser = users[msg.sender]; require(currentUser.status == UserLoginStatus.Online); currentUser.status = UserLoginStatus.Offline; userOnlineCount--; } function authenticate(address _user, string _name, string _password) private view returns(bool) { // Authenticate Caller User by verifying password return(users[_user].passwordHash == keccak256(_password, _name)); } }
Authenticate Caller User by verifying password
function authenticate(address _user, string _name, string _password) private view returns(bool) { return(users[_user].passwordHash == keccak256(_password, _name)); }
12,661,603
pragma solidity ^0.4.19; //import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; import "./oraclizeAPI.sol"; //import "github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol"; import "./SafeMath.sol"; //import "github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol"; import "./Ownable.sol"; //import "github.com/OpenZeppelin/zeppelin-solidity/contracts/token/BurnableToken.sol"; import "./BurnableToken.sol"; import "./Standard223Token.sol"; import './RefundVault.sol'; contract DGTX is oraclizeAPI, Ownable, RefundVault, BurnableToken, Standard223Token { string public constant name = "DigitexFutures"; string public constant symbol = "DGTX"; uint8 public constant decimals = 18; uint public constant DECIMALS_MULTIPLIER = 10**uint(decimals); uint public ICOstarttime = 1516024800; //2018.1.15 January 15, 2018 2:00:00 PM GMT 1516024800 uint public ICOendtime = 1518757200; //2018.2.15 February 16, 2018 5:00:00 AM GMT 1518757200 uint public minimumInvestmentInWei = DECIMALS_MULTIPLIER / 100; uint public maximumInvestmentInWei = 1000 * 1 ether; address saleWalletAddress; uint256 public constant softcapInTokens = 25000000 * DECIMALS_MULTIPLIER; //25000000 * DECIMALS_MULTIPLIER; uint256 public constant hardcapInTokens = 650000000 * DECIMALS_MULTIPLIER; uint256 public totaltokensold = 0; uint public USDETH = 1205; uint NumberOfTokensIn1USD = 100; //RefundVault public vault; bool public isFinalized = false; event Finalized(); event newOraclizeQuery(string description); event newETHUSDPrice(string price); function increaseSupply(uint value, address to) public onlyOwner returns (bool) { totalSupply = totalSupply.add(value); balances[to] = balances[to].add(value); Transfer(0, to, value); return true; } /*function decreaseSupply(uint value, address from) public onlyOwner returns (bool) { balances[from] = balances[from].sub(value); totalSupply = totalSupply.sub(value); Transfer(from, 0, value); return true; }*/ function burn(uint256 _value) public { require(0 != _value); super.burn(_value); Transfer(msg.sender, 0, _value); } /*function StartNextCampain(uint _ICOstarttime, uint _ICOendtime, uint _minimumInvestment, uint _maximumInvestment, uint _NumberOfTokensIn1USD) public onlyOwner { require(!ICOactive()); require(State.Released == vault_state); ICOstarttime = _ICOstarttime; ICOendtime = _ICOendtime; minimumInvestmentInWei = _minimumInvestment; maximumInvestmentInWei = _maximumInvestment; NumberOfTokensIn1USD = _NumberOfTokensIn1USD; UpdateUSDETHPriceAfter(0); }*/ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); uint256 localOwnerBalance = balances[owner]; balances[newOwner] = balances[newOwner].add(localOwnerBalance); balances[owner] = 0; vault_wallet = newOwner; Transfer(owner, newOwner, localOwnerBalance); super.transferOwnership(newOwner); } function finalize() public { require(!isFinalized); require(ICOendtime < now); finalization(); Finalized(); isFinalized = true; } function depositFunds() internal { vault_deposit(msg.sender, msg.value * 96 / 100); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); uint256 refundedTokens = balances[msg.sender]; balances[owner] = balances[owner].add(refundedTokens); totaltokensold = totaltokensold.sub(refundedTokens); balances[msg.sender] = 0; Transfer(msg.sender, owner, refundedTokens); vault_refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault_releaseDeposit(); } else { vault_enableRefunds(); } } function releaseUnclaimedFunds() onlyOwner public { require(vault_state == State.Refunding && now >= refundDeadline); vault_releaseDeposit(); } function goalReached() public view returns (bool) { return totaltokensold >= softcapInTokens; } /*function __callback(bytes32 myid, string result) { require (msg.sender == oraclize_cbAddress()); newETHUSDPrice(result); USDETH = parseInt(result, 0); if ((now < ICOendtime) && (totaltokensold < hardcapInTokens)) { UpdateUSDETHPriceAfter(day); //update every 24 hours } }*/ function UpdateUSDETHPriceAfter (uint delay) private { newOraclizeQuery("Update of USD/ETH price requested"); //oraclize_query(delay, "URL", "json(https://api.etherscan.io/api?module=stats&action=ethprice&apikey=YourApiKeyToken).result.ethusd"); } function DGTX() public payable { totalSupply = 1000000000 * DECIMALS_MULTIPLIER; balances[owner] = totalSupply; vault_wallet = owner; Transfer(0x0, owner, totalSupply); initializeSaleWalletAddress(); UpdateUSDETHPriceAfter(0); } function initializeSaleWalletAddress() private { saleWalletAddress = 0xd8A56FB51B86e668B5665E83E0a31E3696578333; } /*function SendEther ( uint _amount) onlyOwner public { require(this.balance > _amount); owner.transfer(_amount); } */ function () payable { if (msg.sender != owner) { buy(); } } function ICOactive() public view returns (bool success) { if (ICOstarttime < now && now < ICOendtime && totaltokensold < hardcapInTokens) { return true; } return false; } function buy() payable { require (msg.value >= minimumInvestmentInWei && msg.value <= maximumInvestmentInWei); require (ICOactive()); uint256 NumberOfTokensToGive = msg.value.mul(USDETH).mul(NumberOfTokensIn1USD); if(now <= ICOstarttime + week) { NumberOfTokensToGive = NumberOfTokensToGive.mul(120).div(100); } else if(now <= ICOstarttime + 2*week){ NumberOfTokensToGive = NumberOfTokensToGive.mul(115).div(100); } else if(now <= ICOstarttime + 3*week){ NumberOfTokensToGive = NumberOfTokensToGive.mul(110).div(100); } else{ NumberOfTokensToGive = NumberOfTokensToGive.mul(105).div(100); } uint256 localTotaltokensold = totaltokensold; require(localTotaltokensold + NumberOfTokensToGive <= hardcapInTokens); totaltokensold = localTotaltokensold.add(NumberOfTokensToGive); address localOwner = owner; balances[msg.sender] = balances[msg.sender].add(NumberOfTokensToGive); balances[localOwner] = balances[localOwner].sub(NumberOfTokensToGive); Transfer(localOwner, msg.sender, NumberOfTokensToGive); saleWalletAddress.transfer(msg.value - msg.value * 96 / 100); if(!goalReached() && (RefundVault.State.Active == vault_state)) { depositFunds(); } else { if(RefundVault.State.Active == vault_state) {vault_releaseDeposit();} localOwner.transfer(msg.value * 96 / 100); } } }
RefundVault public vault;
{ string public constant name = "DigitexFutures"; string public constant symbol = "DGTX"; uint8 public constant decimals = 18; uint public constant DECIMALS_MULTIPLIER = 10**uint(decimals); uint public minimumInvestmentInWei = DECIMALS_MULTIPLIER / 100; uint public maximumInvestmentInWei = 1000 * 1 ether; address saleWalletAddress; uint256 public constant hardcapInTokens = 650000000 * DECIMALS_MULTIPLIER; uint256 public totaltokensold = 0; uint public USDETH = 1205; uint NumberOfTokensIn1USD = 100; bool public isFinalized = false; event Finalized(); event newOraclizeQuery(string description); event newETHUSDPrice(string price); import "./oraclizeAPI.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; import "./BurnableToken.sol"; function increaseSupply(uint value, address to) public onlyOwner returns (bool) { totalSupply = totalSupply.add(value); balances[to] = balances[to].add(value); Transfer(0, to, value); return true; } totalSupply = totalSupply.sub(value); Transfer(from, 0, value); return true; balances[from] = balances[from].sub(value); }*/
13,031,186
pragma solidity ^0.4.11; import '../zeppelin-solidity/contracts/token/StandardToken.sol'; import '../zeppelin-solidity/contracts/ownership/Ownable.sol'; import '../zeppelin-solidity/contracts/math/SafeMath.sol'; //import 'github.com/OpenZeppelin/zeppelin-solidity/contracts/token/StandardToken.sol'; //import 'github.com/OpenZeppelin/zeppelin-solidity/contracts/ownership/Ownable.sol'; //import 'github.com/OpenZeppelin/zeppelin-solidity/contracts/math/SafeMath.sol'; contract BaseToken is StandardToken, Ownable { using SafeMath for uint256; //struct Reward { // uint value; // uint timestamp; //} function () { //if ether is sent to this address, send it back. throw; } string public name; uint8 public decimals; string public symbol; string public version = 'H1.3'; //uint32 public multiplier = 0.8861425; // address => struct mapping did not work for some reason //mapping (address => Reward) reward; mapping (address => uint) rewValue; mapping (address => uint) rewTimestamp; address rewardTokenOwner; // reward coin owner uint rewardStart; // start of the rewarding peroid uint constant ds = 3 * 30 * 24 * 60 * 60; // period length in seconds (ca. 3 months in seconds, every period has it's own reward rate set in the array below) uint[] rewardPerPeriod; // contains the rewared for any given (ds long) period. Period 0 is starting from rewardStart function BaseToken() { name = "BaseCoin"; decimals = 4; // WARNING! do not change this without modifying reward calculation balances[msg.sender] = 25000000 * 10000; totalSupply = 25000000 * 10000; symbol = "BASE"; rewardPerPeriod.push(50000); rewardPerPeriod.push(44308); rewardPerPeriod.push(39263); rewardPerPeriod.push(34793); rewardPerPeriod.push(30832); rewardPerPeriod.push(27322); rewardPerPeriod.push(24211); rewardPerPeriod.push(21455); rewardPerPeriod.push(19012); rewardPerPeriod.push(16847); rewardPerPeriod.push(14929); rewardPerPeriod.push(13230); rewardPerPeriod.push(11723); rewardPerPeriod.push(10389); rewardPerPeriod.push( 9206); rewardPerPeriod.push( 8158); rewardPerPeriod.push( 7229); rewardPerPeriod.push( 6406); rewardPerPeriod.push( 5677); rewardPerPeriod.push( 5030); } /* Approves and then calls the receiving contract */ // TODO: needed? function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } /************************/ /* Init functions */ /************************/ function setRewardTokenOwner(address _owner) onlyOwner { require(rewardTokenOwner == address(0)); rewardTokenOwner = _owner; } function setRewardStart(uint _start) onlyOwner { require(rewardStart == 0); rewardStart = _start; } /************************/ /* Transfer the balance from owner's account to another account */ function transfer(address _to, uint256 _value) returns (bool success) { uint rewFrom = calculateReward(msg.sender); uint rewTo = calculateReward(_to); if (!super.transfer(_to, _value)) { // if no transaction, then no change in reward return false; } if (rewFrom > 0) { // increase unclaimed reward rewValue[msg.sender] = rewValue[msg.sender].add(rewFrom); rewTimestamp[msg.sender] = now; } if (rewTo > 0 && msg.sender != _to) { // increase unclaimed reward rewValue[_to] = rewValue[_to].add(rewTo); rewTimestamp[_to] = now; } } /* Transfer the balance from one account to another account */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint rewFrom = calculateReward(_from); uint rewTo = calculateReward(_to); if (!super.transferFrom(_from, _to, _value)) { // if no transaction, then no change in reward return false; } if (rewFrom > 0) { // increase unclaimed reward rewValue[_from] = rewValue[_from].add(rewFrom); rewTimestamp[_from] = now; } if (rewTo > 0 && _from != _to) { // increase unclaimed reward rewValue[_to] += rewValue[_to].add(rewTo); rewTimestamp[_to] = now; } } /* Disable reward calculation to save GAS */ function disableMyReward() { rewTimestamp[msg.sender] = rewardStart + 100 * ds; } /* Enable reward calculation starting now */ function enableMyReward() { rewTimestamp[msg.sender] = now; } /* Internal: calculate the reward for * - one base coin * - for the period between t1 and t2 */ // TODO: visible only for testing, make it internal later function rewardFor(uint t1, uint t2) constant returns (uint reward) { uint periodCnt = rewardPerPeriod.length; if ( t2 <= t1 ) return 0; if ( t2 <= rewardStart ) return 0; if ( t1 >= rewardStart + periodCnt * ds ) return 0; if ( t1 < rewardStart) t1 = rewardStart; // so the next won't overflow uint p1 = (t1 - rewardStart) / ds; if ( t2 > rewardStart + periodCnt * ds) t2 = rewardStart + periodCnt * ds; uint p2 = (t2 - rewardStart) / ds; if (p1 == p2) { // same period return ((t2 - t1) * rewardPerPeriod[p1]) / ds; } else { uint p1end = rewardStart + (p1 + 1) * ds; uint p2start = rewardStart + p2 * ds; reward = ((p1end - t1) * rewardPerPeriod[p1]) / ds; for (uint p = p1 + 1; p < p2; p++) { reward += rewardPerPeriod[p]; } if (t2 == p2start) return reward; reward += ((t2 - p2start) * rewardPerPeriod[p2]) / ds; return reward; } } function calculateReward(address _toAddr) constant returns (uint256 reward) { if (rewardStart <= 0 || now < rewardStart) { return 0; } // max(previous reward update time, rewardStart) uint _from = rewTimestamp[_toAddr]; if (_from == 0) { _from = rewardStart; } // min(now, end of reward period) uint _to = now; // divide by 10000, because of 4 decimals for base coin return balanceOf(_toAddr) * rewardFor(_from, _to) / 10000; } function claimReward(address _to) returns (uint256 reward) { // call by the reward token contract owner require(msg.sender == rewardTokenOwner); require(rewardStart > 0 && rewardStart < now); uint rew = rewValue[_to].add(calculateReward(_to)); // all reward has been claimed rewValue[_to] = 0; rewTimestamp[_to] = now; return rew; } }
Transfer the balance from owner's account to another account / if no transaction, then no change in reward increase unclaimed reward increase unclaimed reward
function transfer(address _to, uint256 _value) returns (bool success) { uint rewFrom = calculateReward(msg.sender); uint rewTo = calculateReward(_to); if (!super.transfer(_to, _value)) { return false; } if (rewFrom > 0) { rewValue[msg.sender] = rewValue[msg.sender].add(rewFrom); rewTimestamp[msg.sender] = now; } if (rewTo > 0 && msg.sender != _to) { rewValue[_to] = rewValue[_to].add(rewTo); rewTimestamp[_to] = now; } }
15,842,711
//SPDX-License-Identifier: GNU General Public License v3.0 // ******,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,**,,,,,,,,,,,,,,,,,,,,,,,,,,,,************ // *******,,,,,*,,,,*,*,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,#,/****/**//*//**#**** // ************* *,,*,*,/,,,..............,,,,,,,,,,,,,,,,,,,,*/(,/****(/,(*//////***** // ******,,,,*,,,**,,,,*./,,,. ............,,,,,,,,,,,,,,,,,,***/,******/(,(//*/*////*/###, // **,,,,,,,,,,,**,,,*, ,,,,,. ..........,,,,,,,,,,,,,,,,,***,(,******/(,#//**/*///////,###, // **,,,,,,,,,*,*,**,,,*,, ,/**,...*......,,,,,,,,,,,,*,,**//#/,*//******(*(///////////((((##. // *****,,,,,,,,,,,,*,**,,,,,,,,,,. ..*/,,,,**************/*/(*,,,/**/*******//,/*///*///////((##, // ******,,,,,,,,,,,,*,*,,,,,,,.,,,,.....,,,,**.,/,**.,,******,**************//*,////////////(((###%, // ********,*,,,,,,,*,,*,*,,,,,,,,,.....,,,. ...,,/,**.,/,,******,,,,**********/**/**///**////(((###%%, // ********,*,,,,,,,,*,*,/*,*,,,,,.. .,,.....,,,,,*/.*/.,/**,,,,,,************///**,///*//////((((####%%( // **/********,**,,,,,*,,,,,,,,,.,,,,,,,....,,,,...,*(,/*.,/,,*****,,,*******,***//,,/***///////((######%%#/, // **********,,**,,,****,,,,,*,,,,,,,,....,,**,,,****(,**,,(***,********,,****////(,(*///////////(((#####%%%, // ************,,***,,,****,,,,***,,...,,,,,,....,,*/**(,/*,,(//***,,,***********///(,/**/////(////(########%% // ,///********,,,***,,,*****,,*,,******,,,,,****,,,,**/,/**,/,,,*********////******(,(//((////*//((########%%&, // *//*********,,,,*****,,,*******,*********,********/(,/*,,(//****////***,,,**//(/(,(((///*//((((#######%%%%%** // //*/************,,*****///*/*//****,,,*****,,,,***,//,/**,/*///***,,,**//((////*((*////((((((((((#######%%%%(, // *,(******************,**(/(/*****//**,,,,**********(,/****/****////////****//(((#/(((((((///(((((######%%#%%,, // /***/*/*/*//(((############%(##((((///////***/**(,#.,/*/,/(*///(///////((##%%%%&%&%&&&&&&&&&&&&&&&%%%###%#%%%* // *&/**//*/((###%&&#%%%%%%%%%%%#(((((((((###/(#%,,,,//*******/**,,*/((#&%%#%#######%&&&&&&&&&&&&@&&&&&&%%%%%##&@(, // &&&(*///((((#%%%(#*******///*//////(#%####(%,(******,******////((#%%%%%%%%%(////////////////(&&&&@&&&&%%%%#&&&@/, // %&,#%/**(((/#/#/*(*%***************/////#%%#(((/*,,**********///(%%%%%&%#////////////////////@%%%&@&&%&&%%#%&%#&, // (,*&&**(##,********,#/***************/////%(/******************#%%%%%////////////////****(//%%%%%%%##&&%%%&&##&#, // //*/&&#,/,,(*//********,/#*,,,,,,,,**/#%//*//****,,,,,,,****//(%#%%%%&&@%(/////***,*/&/*/((((((#%%&%#%%#@@@&#%&#* // #*#,(&/,,,,,**,*%,//*********************/******,,**********//(##%%%#%%%%%%*********///(//#%#(&/((/#####%@##@#&#* // #%**,#/,,,,,,,,,,*,,,,*##(***,,/,*((,.,*,*******,,,,,****,,,,*(###%%%%#%,*/((/****(*/#%#***///////((((#%%%###@%#, // *%*(#&/*,,,,,,,,,,,,,,,,,,,,.. .,*,,*********************//###%%%////*/*,****,*************////((((##%@%%%%##, // *(,(#**,,,,,,,,,,,,,,,,,,... .,(,.*,,*****/***,,,,,,,,***//####%*,****/,*/*,,,,,,*,*******////((((##%#&&#%%%// // (//(*******,,,,,,,,,,,,,,,,......,/,*,,,,,,********,*********/##%%//*,,,*,*//*,,,,,,*******////(((###%%%%%%&%%%# // ((#*/*********,,,,,,,,,,,,,,,,,,./,,,**,****//**,,,,,,,*,,,*(#%%%///////*,****,,,,,,,,,,,,,,,,,,###%%%%%%&#%%%( // ((((#*#*********,,,,,,,,,,,,,,,,,*,,******///******,,,*/***/##%%(/****//(%/,,,,,,,,,,,,,,,,***##%%%%%%%&%&%%%%/ // ((((((/*#***************,,,,,,***#*//**(//(///**,,****,****(#%%////(/(((,,,,,,*************##%%%%%%&%&%&%%%%( // ((((((((#*(////**********************,(/*/(//***,,,***,*/**#%%%((#/%(*/,**************###%%%%%%%%&%&&&&%%%%# // (((((((((*(%%(**///*********************//(//****,***,****##%%#%******************#%%%%&&%%&@&&&&&&&&%%%% // ((((((((#(/#//((**(%(***************,*****#//*////(//(((#/%#%%(****************###%#@&%%%&&%&&&&&&&&%%% // (((((((#(#%//////////************,,,,****(//%#(/***/(#&&@%%&%***************%#%%%&%%&&%%&&&&&&&&&%%%%% // (((((((((((#(///////#/*****%/*****,,,***(#/(#%&&%%%%%%&&@&&&&&(***********#@%#%%%%&%%%&&&&&&&&&&&&&%% // (%(((((((((/(////*((******#&#/****#*,,,********(%(%%%%%%%%%%*//#*******&&@%%%%%&&&%&&&&&&&&&&&&&&%& // ##%(((((#(/%%*////********@&%&&&&&&&&&&&(&*********//%&&&&&&&@@@@&&@@%%%%%%%%%%%%&@@&&&&&&&%&%%%% // /#*%//%&&%%/////**********/@@@@@@@@@@@@@&/,,,,,,,**%@@@@@@@@@@@@@@&%%%%%%%%%%%%%&%&&@@&%&&#&%%% // ///////(%/#/////********,#/**,,,,,,,,,,,,,,,,,,,,,*******/////%%%%&&%%%%%%%%%%%&&&&&@&%%%%%%%% // /*/*///////#//*************,,,,,,,,,,*///******///(((#((/////((((#%%%%%%%%%%%%%%%&&%%%%%%%%% // //******/(//**********#*******(&&&&&&&&&&&&&&&&&&&&&&@@@@&&%##%%%%&%%%%%%%%%%%&%%%%%%%%%&* // *(/******///**/%#(****%*&&&&%******,,. .,***********/////(%%&&@@@&&%%%&&@@%%%&%%%%%%%%%&( // (,(*******((/*****************,,,,,,,,,,,,,,,,,********/(######%#%%%%%%%%%&&&%%%%%%%&#% // ((,#*/***********************/////////****/////((#%%&&&%%%####%##%%%%%%%%%%%%%%%%&%&& // //((/*(*///********************///((##%%&&&&&&&&&&%%%####(#((##%%%%%%%%%%%%%%%&#&&&&* // ,((//#*/*#******************////////////((#(#((#%#&%####((#%%%%%%%%%%%%%%&%%%&&%&&* // ((((((*(/,(*********************************//////((((#(######%%%%%%&#%%%&&&&&% // ##(((#*((#,#***********************/,***(***/////////(((((##%%%%%&%&&%%&&&&& // ##((#/#(((,#**************(/,,*,/,//((/,#**,/%(////(((((%#%%%%%&&&%%&&&&& // ((((((((((//(,#*/*###/,,,/#,%(,#&&&&&#&&@*(*(#%//*/%%&&(#%&#&%&&&&%&&&& // ((()))))(/(////,,*##/,*/(((,(%%@*,,,**&@*%((/(((#(%&&#((&%&%%%&&&& // (()))))))(///((/(/**(/*(#,,#@*//***/*(##(@/(/((/(#&#&&%&%%%&&& // ()()()(()#(((/*(((*@*&,/(@@#(****//((@@@/%(#%&#%#&%%&&&() // ())))#####%(&/&,@@@@@(%/,/(####*(&(@@@@@@&&&&&&&()) // &&(%*%@@@@@#(%%%#**#%%&%@@@@@@@()()()()()()) // ()()()&^()()@@@@@@@@@@@@@@@&*&()()())() // // // /* *Welcome to the Satoshiverse! The Satoshiverse is an epic comic NFT collaboration between Apollo NFT Studios, Jose Delbo, and YOU, the NFT community. *It tells the story of our hero, Satoshi The Creator and his quest to save the world from the Defenders of Fiat and the many other foes who lie ahead. */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "../utils/Operatorable.sol"; import "../helpers/StringHelper.sol"; /** * SatoshiVerse Legionnaire Avatar NFT Contract V1 * Provided by Satoshiverse LLC * Authored by brnaldomesi a Senior Solidity Developer @ Herasoft */ contract Legionnaire is ERC721Enumerable, ERC721URIStorage, Operatorable { // Token URI string public baseURI = "https://ipfs.io/ipfs/"; constructor() ERC721("Satoshi's Legions - The Legionnaires", "LEGIONNAIRES") { } // A function for the Operator to set the Base Token URI function setBaseTokenURI(string memory _baseTokenURI) external onlyOperator { baseURI = _baseTokenURI; } // Call to View the Base URI function _baseURI() internal view override returns (string memory) { return baseURI; } // Secure internal function to safely transfer a specific tokenId from an address to another one function _beforeTokenTransfer( address _from, address _to, uint256 _tokenId ) internal override(ERC721, ERC721Enumerable) { ERC721Enumerable._beforeTokenTransfer(_from, _to, _tokenId); } // A secure function for a user to be able to burn their Legionniare if desired function _burn(uint256 _tokenId) internal override(ERC721, ERC721URIStorage) { ERC721URIStorage._burn(_tokenId); } // Interface Support for the 721 Libraries function supportsInterface(bytes4 _interfaceId) public view virtual override(AccessControl, ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(_interfaceId); } // A secure function to change the default behavior of the tokenURI to return the placeholder URI for Legionniares that havn't been revealed yet function tokenURI(uint256 _tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { string memory _tokenURI = ERC721URIStorage.tokenURI(_tokenId); uint256 lastPosition = bytes(_tokenURI).length; string memory lastPrefix = StringHelper.substring(_tokenURI, lastPosition - 11, lastPosition); if(StringHelper.compareStrings(lastPrefix, "placeholder")) { return "https://ipfs.io/ipfs/QmWL9iFWyYrRPPxF8habN4FkcQYmwHinE8Zdw7B6vL4VrT"; } else { return _tokenURI; } } // A srcure function for the Operator to safely mint a specific tokenId if necessary function safeMint(address to, uint256 tokenId) external onlyOperator { _safeMint(to, tokenId); } // A secure function for the Operator to safely burn a specific tokenId if necessary function burn(uint256 _tokenId) external onlyOperator { require(super._exists(_tokenId), "LEGIONNARE BURN: TOKEN_ID_INVALID"); _burn(_tokenId); } // A secure function for the SatoshiVerse Contract to set the tokenURI function setTokenURI(uint256 tokenId, string memory _tokenURI) external onlyOperator { ERC721URIStorage._setTokenURI(tokenId, _tokenURI); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @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]; } } } //SPDX-License-Identifier: GNU General Public License v3.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; contract Operatorable is Ownable, AccessControl { bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant URI_SETTER_ROLE = keccak256("URI_SETTER_ROLE"); /** * @dev Restricted to members of the `operator` role. */ modifier onlyOperator() { require(hasRole(OPERATOR_ROLE, msg.sender), "Operatorable: CALLER_NO_OPERATOR_ROLE"); _; } modifier onlyURISetter() { require(hasRole(URI_SETTER_ROLE, msg.sender), "Settable: CALLER_NO_URI_SETTER_ROLE"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(OPERATOR_ROLE, msg.sender); _setupRole(URI_SETTER_ROLE, msg.sender); } /** * @dev Add an `_account` to the `operator` role. */ function addOperator(address _account) public onlyOwner { grantRole(OPERATOR_ROLE, _account); } /** * @dev Remove an `_account` from the `operator` role. */ function removeOperator(address _account) public onlyOwner { revokeRole(OPERATOR_ROLE, _account); } function addURISetter(address _account) public onlyOwner { grantRole(URI_SETTER_ROLE, _account); } function removeURISetter(address _account) public onlyOwner { revokeRole(URI_SETTER_ROLE, _account); } /** * @dev Check if an _account is operator. */ function isOperator(address _account) public view returns (bool) { return hasRole(OPERATOR_ROLE, _account); } /** * @dev Check if an _account is operator. */ function isURISetter(address _account) public view returns (bool) { return hasRole(URI_SETTER_ROLE, _account); } } //SPDX-License-Identifier: GNU General Public License v3.0 pragma solidity ^0.8.0; library StringHelper { function substring(string memory str, uint startIndex, uint endIndex) pure internal returns (string memory) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex-startIndex); for(uint i = startIndex; i < endIndex; i++) { result[i-startIndex] = strBytes[i]; } return string(result); } function compareStrings(string memory a, string memory b) pure internal returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
A srcure function for the Operator to safely mint a specific tokenId if necessary
function safeMint(address to, uint256 tokenId) external onlyOperator { _safeMint(to, tokenId); }
29,316
//SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Base64.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./ILogbook.sol"; import "./Royalty.sol"; import "./NFTSVG.sol"; contract Logbook is ERC721, Ownable, ILogbook, Royalty { uint256 private constant _ROYALTY_BPS_LOGBOOK_OWNER = 8000; uint256 private constant _ROYALTY_BPS_COMMISSION_MAX = 10000 - _ROYALTY_BPS_LOGBOOK_OWNER; uint256 private constant _PUBLIC_SALE_ON = 1; uint256 private constant _PUBLIC_SALE_OFF = 2; uint256 public publicSale = _PUBLIC_SALE_OFF; uint256 public publicSalePrice; // contentHash to log mapping(bytes32 => Log) public logs; // tokenId to logbook mapping(uint256 => Book) private _books; // starts at 1501 since 1-1500 are reseved for Traveloggers claiming using Counters for Counters.Counter; Counters.Counter internal _tokenIdCounter = Counters.Counter(1500); /** * @dev Throws if called by any account other than the logbook owner. */ modifier onlyLogbookOwner(uint256 tokenId_) { if (!_isApprovedOrOwner(msg.sender, tokenId_)) revert Unauthorized(); _; } constructor(string memory name_, string memory symbol_) ERC721(name_, symbol_) {} /// @inheritdoc ILogbook function setTitle(uint256 tokenId_, string calldata title_) external onlyLogbookOwner(tokenId_) { emit SetTitle(tokenId_, title_); } /// @inheritdoc ILogbook function setDescription(uint256 tokenId_, string calldata description_) external onlyLogbookOwner(tokenId_) { emit SetDescription(tokenId_, description_); } /// @inheritdoc ILogbook function setForkPrice(uint256 tokenId_, uint256 amount_) external onlyLogbookOwner(tokenId_) { _books[tokenId_].forkPrice = amount_; emit SetForkPrice(tokenId_, amount_); } /// @inheritdoc ILogbook function multicall(bytes[] calldata data) external payable returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); require(success); results[i] = result; } return results; } /// @inheritdoc ILogbook function publish(uint256 tokenId_, string calldata content_) external onlyLogbookOwner(tokenId_) { bytes32 contentHash = keccak256(abi.encodePacked(content_)); // log Log memory log = logs[contentHash]; if (log.author == address(0)) { logs[contentHash] = Log(msg.sender, tokenId_); emit Content(msg.sender, contentHash, content_); } // logbook _books[tokenId_].logCount++; _books[tokenId_].contentHashes.push(contentHash); emit Publish(tokenId_, contentHash); } /// @inheritdoc ILogbook function fork(uint256 tokenId_, uint32 endAt_) external payable returns (uint256 tokenId) { (Book memory book, uint256 newTokenId) = _fork(tokenId_, endAt_); tokenId = newTokenId; if (msg.value > 0) { address logbookOwner = ERC721.ownerOf(tokenId_); _splitRoyalty(tokenId_, book, logbookOwner, msg.value, RoyaltyPurpose.Fork, address(0), 0); } } /// @inheritdoc ILogbook function forkWithCommission( uint256 tokenId_, uint32 endAt_, address commission_, uint256 commissionBPS_ ) external payable returns (uint256 tokenId) { if (commissionBPS_ > _ROYALTY_BPS_COMMISSION_MAX) revert InvalidBPS(0, _ROYALTY_BPS_COMMISSION_MAX); (Book memory book, uint256 newTokenId) = _fork(tokenId_, endAt_); tokenId = newTokenId; if (msg.value > 0) { address logbookOwner = ERC721.ownerOf(tokenId_); _splitRoyalty(tokenId_, book, logbookOwner, msg.value, RoyaltyPurpose.Fork, commission_, commissionBPS_); } } /// @inheritdoc ILogbook function donate(uint256 tokenId_) external payable { if (msg.value <= 0) revert ZeroAmount(); if (!_exists(tokenId_)) revert TokenNotExists(); Book memory book = _books[tokenId_]; address logbookOwner = ERC721.ownerOf(tokenId_); _splitRoyalty(tokenId_, book, logbookOwner, msg.value, RoyaltyPurpose.Donate, address(0), 0); emit Donate(tokenId_, msg.sender, msg.value); } /// @inheritdoc ILogbook function donateWithCommission( uint256 tokenId_, address commission_, uint256 commissionBPS_ ) external payable { if (msg.value <= 0) revert ZeroAmount(); if (!_exists(tokenId_)) revert TokenNotExists(); if (commissionBPS_ > _ROYALTY_BPS_COMMISSION_MAX) revert InvalidBPS(0, _ROYALTY_BPS_COMMISSION_MAX); Book memory book = _books[tokenId_]; address logbookOwner = ERC721.ownerOf(tokenId_); _splitRoyalty(tokenId_, book, logbookOwner, msg.value, RoyaltyPurpose.Donate, commission_, commissionBPS_); emit Donate(tokenId_, msg.sender, msg.value); } /// @inheritdoc ILogbook function getLogbook(uint256 tokenId_) external view returns (Book memory book) { book = _books[tokenId_]; } /// @inheritdoc ILogbook function getLogs(uint256 tokenId_) external view returns (bytes32[] memory contentHashes, address[] memory authors) { Book memory book = _books[tokenId_]; uint32 logCount = book.logCount; contentHashes = _logs(tokenId_); authors = new address[](logCount); for (uint32 i = 0; i < logCount; i++) { bytes32 contentHash = contentHashes[i]; authors[i] = logs[contentHash].author; } } /// @inheritdoc ILogbook function claim(address to_, uint256 logrsId_) external onlyOwner { if (logrsId_ < 1 || logrsId_ > 1500) revert InvalidTokenId(1, 1500); _safeMint(to_, logrsId_); _books[logrsId_].createdAt = uint160(block.timestamp); } /// @inheritdoc ILogbook function publicSaleMint() external payable returns (uint256 tokenId) { if (publicSale != _PUBLIC_SALE_ON) revert PublicSaleNotStarted(); if (msg.value < publicSalePrice) revert InsufficientAmount(msg.value, publicSalePrice); // forward value address deployer = owner(); (bool success, ) = deployer.call{value: msg.value}(""); require(success); // mint tokenId = _mint(msg.sender); } /// @inheritdoc ILogbook function setPublicSalePrice(uint256 price_) external onlyOwner { publicSalePrice = price_; } /// @inheritdoc ILogbook function turnOnPublicSale() external onlyOwner { publicSale = _PUBLIC_SALE_ON; } /// @inheritdoc ILogbook function turnOffPublicSale() external onlyOwner { publicSale = _PUBLIC_SALE_OFF; } function tokenURI(uint256 tokenId_) public view override returns (string memory) { if (!_exists(tokenId_)) revert TokenNotExists(); Book memory book = _books[tokenId_]; uint32 logCount = book.logCount; string memory tokenName = string(abi.encodePacked("Logbook #", Strings.toString(tokenId_))); string memory description = "A book that records owners' journey in Matterverse."; string memory attributeLogs = string( abi.encodePacked('{"trait_type": "Logs","value":"', Strings.toString(logCount), '"}') ); NFTSVG.SVGParams memory svgParams = NFTSVG.SVGParams({ logCount: logCount, transferCount: book.transferCount, createdAt: book.createdAt, tokenId: tokenId_ }); string memory image = Base64.encode(bytes(NFTSVG.generateSVG(svgParams))); string memory json = Base64.encode( bytes( string( abi.encodePacked( '{"name": "', tokenName, '", "description": "', description, '", "attributes": [', attributeLogs, '], "image": "data:image/svg+xml;base64,', image, '"}' ) ) ) ); string memory output = string(abi.encodePacked("data:application/json;base64,", json)); return output; } /** * @notice Get logs of a book * @param tokenId_ Logbook token id */ function _logs(uint256 tokenId_) internal view returns (bytes32[] memory contentHashes) { Book memory book = _books[tokenId_]; contentHashes = new bytes32[](book.logCount); uint32 index = 0; // copy from parents Book memory parent = _books[book.parent]; uint32 takes = book.endAt; bool hasParent = book.parent == 0 ? false : true; while (hasParent) { bytes32[] memory parentContentHashes = parent.contentHashes; for (uint32 i = 0; i < takes; i++) { contentHashes[index] = parentContentHashes[i]; index++; } if (parent.parent == 0) { hasParent = false; } else { takes = parent.endAt; parent = _books[parent.parent]; } } // copy from current bytes32[] memory currentContentHashes = book.contentHashes; for (uint32 i = 0; i < currentContentHashes.length; i++) { contentHashes[index] = currentContentHashes[i]; index++; } } function _mint(address to) internal returns (uint256 tokenId) { _tokenIdCounter.increment(); tokenId = _tokenIdCounter.current(); _safeMint(to, tokenId); _books[tokenId].createdAt = uint160(block.timestamp); } function _fork(uint256 tokenId_, uint32 endAt_) internal returns (Book memory newBook, uint256 newTokenId) { if (!_exists(tokenId_)) revert TokenNotExists(); Book memory book = _books[tokenId_]; uint32 maxEndAt = uint32(book.contentHashes.length); uint32 logCount = book.logCount; if (logCount <= 0 || endAt_ <= 0 || maxEndAt < endAt_) revert InsufficientLogs(maxEndAt); if (msg.value < book.forkPrice) revert InsufficientAmount(msg.value, book.forkPrice); // mint new logbook newTokenId = _mint(msg.sender); bytes32[] memory contentHashes = new bytes32[](0); newBook = Book({ endAt: endAt_, logCount: logCount - maxEndAt + endAt_, transferCount: 1, createdAt: uint160(block.timestamp), parent: tokenId_, forkPrice: 0 ether, contentHashes: contentHashes }); _books[newTokenId] = newBook; emit Fork(tokenId_, newTokenId, msg.sender, endAt_, msg.value); } /** * @notice Split royalty payments * @dev No repetitive checks, please make sure all arguments are valid * @param tokenId_ Logbook token id * @param book_ Logbook to be split royalty * @param amount_ Total amount to split royalty * @param purpose_ Payment purpose * @param commission_ commission_ Address (frontend operator) to earn commission * @param commissionBPS_ Basis points of the commission */ function _splitRoyalty( uint256 tokenId_, Book memory book_, address logbookOwner_, uint256 amount_, RoyaltyPurpose purpose_, address commission_, uint256 commissionBPS_ ) internal { uint32 logCount = book_.logCount; bytes32[] memory contentHashes = _logs(tokenId_); // fees calculation SplitRoyaltyFees memory fees; bool isNoCommission = commission_ == address(0) || commissionBPS_ == 0; if (!isNoCommission) { fees.commission = (amount_ * commissionBPS_) / 10000; } if (logCount <= 0) { fees.logbookOwner = amount_ - fees.commission; } else { fees.logbookOwner = (amount_ * _ROYALTY_BPS_LOGBOOK_OWNER) / 10000; fees.perLogAuthor = (amount_ - fees.logbookOwner - fees.commission) / logCount; } // split royalty // -> logbook owner _balances[logbookOwner_] += fees.logbookOwner; emit Pay({ tokenId: tokenId_, sender: msg.sender, recipient: logbookOwner_, amount: fees.logbookOwner, purpose: purpose_ }); // -> commission if (!isNoCommission) { _balances[commission_] += fees.commission; emit Pay({ tokenId: tokenId_, sender: msg.sender, recipient: commission_, amount: fees.commission, purpose: purpose_ }); } // -> logs' authors if (logCount > 0) { for (uint32 i = 0; i < logCount; i++) { Log memory log = logs[contentHashes[i]]; _balances[log.author] += fees.perLogAuthor; emit Pay({ tokenId: tokenId_, sender: msg.sender, recipient: log.author, amount: fees.perLogAuthor, purpose: purpose_ }); } } } function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual override { super._afterTokenTransfer(from_, to_, tokenId_); // Call parent hook _books[tokenId_].transferCount++; // warm up _balances[to] to reduce gas of SSTORE on _splitRoyalty if (_balances[to_] == 0) { _balances[to_] = 1 wei; } } }
@inheritdoc ILogbook
function setPublicSalePrice(uint256 price_) external onlyOwner { publicSalePrice = price_; }
1,831,183
./full_match/1313161554/0x90C6B69383695b4Dc4125ca010C61f78dff93fb0/sources/contracts/UTTProxy.sol
Converts a byte value to its readable char value. b byte value return c the value as a readable char/
function char(bytes1 b) internal pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); }
13,234,583
pragma solidity ^0.4.24; /** * Ready Player ONE * @title -ReadyPlayerONE */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract RP1events { // 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 rp1Amount, 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 rp1Amount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 rp1Amount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 rp1Amount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is RP1events {} contract ReadyPlayerONE is modularLong { using SafeMath for *; using NameFilter for string; using RP1KeysCalcLong for uint256; address community_addr = 0x4c20d0ab4baadbce39fe6ac94cefd99b7686339c; address marketing_addr = 0x9386b3cc1155764b60ca81fc83761777f6487ac3; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x15247cF99b5870F54EA17e85E1aF8667a58a6644); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Ready Player ONE"; string constant public symbol = "RP1"; uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. //todo 1hours uint256 constant private rndInit_ = 1 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_ = 12 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => RP1datasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => RP1datasets.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 => RP1datasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => RP1datasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => RP1datasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { //玄武 计算的 100-30-18 fees_[0] = RP1datasets.TeamFee(30,0); //52% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot //白虎 fees_[1] = RP1datasets.TeamFee(41,0); //41% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot //青龙 fees_[2] = RP1datasets.TeamFee(60,0); //22% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot //朱雀 fees_[3] = RP1datasets.TeamFee(46,0); //36% to pot, 12% to aff, 2% to com, 1% to pot swap, 3% to air drop pot // (分红, 推广经费) potSplit_[0] = RP1datasets.PotSplit(18,4); //58% to winner, 18% to next round, 2% to com potSplit_[1] = RP1datasets.PotSplit(25,0); //58% to winner, 15% to next round, 2% to com potSplit_[2] = RP1datasets.PotSplit(22,8); //58% to winner, 10% to next round, 2% to com potSplit_[3] = RP1datasets.PotSplit(32,2); //58% to winner, 6% to next round, 2% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RP1datasets.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 RP1datasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RP1datasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not RP1datasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RP1datasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RP1datasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data RP1datasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data RP1datasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit RP1events.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.rp1Amount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit RP1events.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit RP1events.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 RP1events.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 RP1events.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(58)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return 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, RP1datasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RP1events.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.rp1Amount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, RP1datasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit RP1events.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.rp1Amount, _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, RP1datasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter 100eth 1eth if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(RP1datasets.EventReturns memory _eventData_) private returns (RP1datasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, RP1datasets.EventReturns memory _eventData_) private returns (RP1datasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(RP1datasets.EventReturns memory _eventData_) private returns (RP1datasets.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, // rp1 share, and amount reserved for next pot uint256 _win = (_pot.mul(58)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _rp1 = (_pot.mul(potSplit_[_winTID].rp1)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_rp1); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards community_addr.transfer(_com); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // for next round 修改 if (_rp1 > 0){ _res = _res.add(_rp1); } // 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_.rp1Amount = _rp1; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and rp1 */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, RP1datasets.EventReturns memory _eventData_) private returns(RP1datasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _rp1; //修改 community_addr.transfer(_com); // pay 1% out to marketing uint256 _long = _eth / 100; //修改 marketing_addr.transfer(_long); // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit RP1events.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _rp1 = _aff; } // pay out rp1 _rp1 = _rp1.add((_eth.mul(fees_[_team].rp1)) / (100)); if (_rp1 > 0) { community_addr.transfer(_rp1); // set up event data _eventData_.rp1Amount = _rp1.add(_eventData_.rp1Amount); } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit RP1events.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, RP1datasets.EventReturns memory _eventData_) private returns(RP1datasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 3% into airdrop pot uint256 _air = (_eth.mul(3) / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance _eth = _eth.sub(((_eth.mul(18)) / 100)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, RP1datasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit RP1events.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.rp1Amount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == community_addr, "only community can activate" ); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now - rndGap_; round_[1].end = now + rndInit_ ; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library RP1datasets { //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 rp1Amount; // amount distributed to rp1 uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 rp1; // % of buy in thats paid to rp1 holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 rp1; // % of pot thats paid to rp1 holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library RP1KeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface otherFoMo3D { function potSwap() external payable; } interface RP1externalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } interface DiviesInterface { function deposit() external payable; } interface JIincForwarderInterface { function deposit() external payable returns(bool); function status() external view returns(address, address, bool); function startMigration(address _newCorpBank) external returns(bool); function cancelMigration() external returns(bool); function finishMigration() external returns(bool); function setup(address _firstCorpBank) external; } 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 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz use last stored affiliate code if affiliate code was given get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { RP1datasets.EventReturns memory _eventData_ = determinePID(_eventData_); uint256 _pID = pIDxAddr_[msg.sender]; uint256 _affID; if (_affCode == address(0) || _affCode == msg.sender) { _affID = plyr_[_pID].laff; _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { plyr_[_pID].laff = _affID; } } }
505,114
./partial_match/97/0xF452Cece08bEd0Eda428E553fD891B8A12BFc4A2/sources/SOTAMarket.sol
buyer pay itemPrice + marketFee seller receive artistLoyaltyFee itemPrice / 100 artist receive itemPrice (100 - artistLoyaltyFee) referral of buyer receive (marketFee itemPrice / 100) (referralFee / 100)/ buyer pay itemPrice + marketFee seller receive artistLoyaltyFee itemPrice / 100 artist receive itemPrice (100 - artistLoyaltyFee) referral of buyer receive (marketFee itemPrice / 100) (referralFee / 100)/ buyer pay itemPrice + marketFee seller receive itemPrice - itemPrice marketFee / 100 - revenue lastSalePrice[tokenAddress][tokenId] item.loyalty referral of seller receive itemPrice marketFee / 100 (referralFee / 100) referral of buyer receive itemPrice marketFee / 100 (referralFee / 100) creator receive revenue lastSalePrice[tokenAddress][tokenId] loyalty/
function executeOrder(address _buyer, uint256 _itemId, uint256 _quantity, address _paymentToken, uint256 _paymentAmount) private returns(bool) { Item storage item = items[_itemId]; address payable creator = payable(IERC1155(item.tokenAddress).getCreator(item.tokenId)); uint256 loyalty = IERC1155(item.tokenAddress).getLoyaltyFee(item.tokenId); uint256 itemPrice = estimateToken(_paymentToken, item.price.div(item.quantity).mul(_quantity)); require (_paymentAmount >= itemPrice.mul(ZOOM_FEE + marketFee).div(ZOOM_FEE), 'Invalid price'); _paymentAmount = itemPrice.mul(ZOOM_FEE + marketFee).div(ZOOM_FEE); uint256 priceInUsdt = item.price.div(item.quantity).mul(_quantity); ref.buyerRef = getReferralAddress(_buyer); ref.sellerRef = getReferralAddress(item.owner); if (msg.value == 0) { if (item.tokenAddress == farmingContract) { fee.itemFee = itemPrice.mul(marketFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(creator, itemPrice.mul(artistLoyaltyFee).div(ZOOM_FEE)); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - artistLoyaltyFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.itemFee.mul(referralFee).div(ZOOM_FEE)); } fee.sellerFee = itemPrice.mul(firstSellFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - firstSellFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } if (item.tokenAddress == farmingContract) { fee.itemFee = itemPrice.mul(marketFee).div(ZOOM_FEE); creator.transfer(itemPrice.mul(artistLoyaltyFee).div(ZOOM_FEE)); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - artistLoyaltyFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.itemFee.mul(referralFee).div(ZOOM_FEE)); } fee.sellerFee = itemPrice.mul(firstSellFee).div(ZOOM_FEE); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - firstSellFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } } if (lastSalePrice[item.tokenAddress][item.tokenId] < priceInUsdt) { uint256 revenue = (priceInUsdt - lastSalePrice[item.tokenAddress][item.tokenId]).mul(ZOOM_FEE).div(priceInUsdt); if (msg.value > 0) { fee.loyaltyFee = itemPrice.mul(revenue).div(ZOOM_FEE).mul(loyalty).div(ZOOM_FEE); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE).sub(fee.loyaltyFee)); creator.transfer(fee.loyaltyFee); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } fee.loyaltyFee = itemPrice.mul(revenue).div(ZOOM_FEE).mul(loyalty).div(ZOOM_FEE); fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE).sub(fee.loyaltyFee)); IERC20(_paymentToken).transfer(creator, fee.loyaltyFee); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } fee.buyerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); fee.sellerFee = itemPrice.mul(marketFee).div(ZOOM_FEE); if (msg.value == 0) { ERC20(_paymentToken).safeTransferFrom(_buyer, address(this), _paymentAmount); IERC20(_paymentToken).transfer(item.owner, itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { IERC20(_paymentToken).transfer(ref.buyerRef, fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { IERC20(_paymentToken).transfer(ref.sellerRef, fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } payable(item.owner).transfer(itemPrice.mul(ZOOM_FEE - marketFee).div(ZOOM_FEE)); if (ref.buyerRef != address(0)) { ref.buyerRef.transfer(fee.buyerFee.mul(referralFee).div(ZOOM_FEE)); } if (ref.sellerRef != address(0)) { ref.sellerRef.transfer(fee.sellerFee.mul(referralFee).div(ZOOM_FEE)); } } } } IERC1155(item.tokenAddress).safeTransferFrom(address(this), _buyer, item.tokenId, _quantity, abi.encodePacked(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))); lastSalePrice[item.tokenAddress][item.tokenId] = priceInUsdt.mul(ZOOM_FEE + marketFee).div(ZOOM_FEE); item.price = item.price.sub(priceInUsdt); item.quantity = item.quantity.sub(_quantity);
11,438,848
//Address: 0xcc211ae7e10185ec450d9447d617b897a812b544 //Contract name: CryptoAvatars //Balance: 0 Ether //Verification Date: 5/4/2018 //Transacion Count: 1 // CODE STARTS HERE 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; } } pragma solidity ^0.4.18; /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } pragma solidity ^0.4.18; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public; } pragma solidity ^0.4.18; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() public view returns (string _name); function symbol() public view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } pragma solidity ^0.4.18; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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; } } pragma solidity ^0.4.18; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether there is code in the target address * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address address to check * @return whether there is code in the target address */ function isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } } pragma solidity ^0.4.18; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } pragma solidity ^0.4.18; /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is ERC721, ERC721BasicToken { // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function ERC721Token(string _name, string _symbol) public { name_ = _name; symbol_ = _symbol; } /** * @dev Gets the token name * @return string representing the token name */ function name() public view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() public view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * @dev Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Internal function to set the token URI for a given token * @dev Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * @dev Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } pragma solidity ^0.4.21; /** * @title ERC721 Token for Crypto Avatars * @dev Allows to create and "evolve" Crypto Avatars. * Avatars can be created and modified only by a whitelisted account, * Contract owner can be superseded by the contract supervisor in case of emergency. * @author Guerrilla Crypto */ contract CryptoAvatars is ERC721Token, Whitelist { struct CryptoAvatar { uint256 statistics; uint32 avatarType; uint32 level; uint32 experience; uint64 creationTime; bool isHibernated; } /// @dev An array containing the CryptoAvatar struct for all Avatars in existence. The ID /// of each avatar is an index into this array. CryptoAvatar[] avatars; /// @dev Supervisor can take over contract owner address public supervisor; /// @dev allow avatar creation bool public allowAvatarCreation = true; /// @dev The Creation event is fired whenever a new avatar comes into existence. event Creation(uint256 avatarId, uint256 statistics, uint256 avatarType, uint256 level, uint256 experience); /// @dev The Evolution event is fired whenever an avatar evolves (changes its characteristics). event Evolution(uint256 avatarId, uint256 statistics, uint256 avatarType, uint256 level, uint256 experience); /// @dev The SupervisorChanged event is fired whenever the supervisor is changed event SupervisorChanged(address indexed previousSupervisor, address indexed newSupervisor); /// @dev The Hibernated event is fired whenever the avatar is hibernated by the owner event Hibernated(uint256 avatarId); /// @dev The WokenUp event is fired whenever the avatar is woken up by the owner event WokenUp(uint256 avatarId); /// @dev Create token with name and symbol and set the supervisor constructor(address _supervisor) ERC721Token("CryptoAvatars", "AVA") public { // set the supervisor supervisor = _supervisor; // add owner to whitelist addAddressToWhitelist(msg.sender); // add supervisor to whitelist addAddressToWhitelist(supervisor); } /** * @dev Throws if called by any account other than the supervisor. */ modifier onlySupervisor() { require(msg.sender == supervisor); _; } /** * @dev Allows the supervisor to take control of the contract. */ function takeControl() external onlySupervisor { require(owner != supervisor); // new owner is the supervisor owner = supervisor; } /** * @dev Allows the current supervisor to transfer control of the contract to a newSupervisor. * @param newSupervisor The address to transfer to. */ function changeSupervisor(address newSupervisor) external onlySupervisor { require(newSupervisor != supervisor); emit SupervisorChanged(supervisor, newSupervisor); supervisor = newSupervisor; } /** * @dev Allows the supervisor to stop the creation of new avatars. */ function stopAvatarCreation() external onlySupervisor { allowAvatarCreation = false; } /// @notice Returns all the relevant information about a specific avatar. /// @param _id The ID of the avatar function getCryptoAvatar(uint256 _id) external view returns ( uint256 statistics, uint256 avatarType, uint256 level, uint256 experience, uint256 creationTime, bool isHibernated ) { // check if exists require(exists(_id)); CryptoAvatar storage avatar = avatars[_id]; statistics = uint256(avatar.statistics); avatarType = uint256(avatar.avatarType); level = uint256(avatar.level); experience = uint256(avatar.experience); creationTime = uint256(avatar.creationTime); isHibernated = avatar.isHibernated; } /// @dev An external method that creates a new avatar and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Creation event /// and a Transfer event. /// Only whitelisted callers can access this /// @param _avatarType The avatar type /// @param _level The avatar level /// @param _experience The avatar experience. /// @param _statistics The avatar statistics. /// @param _owner The initial owner of this avatar. function createCryptoAvatar( uint256 _statistics, uint256 _avatarType, uint256 _level, uint256 _experience, address _owner ) onlyWhitelisted external { // check if we can create new avatar require(allowAvatarCreation); // check if parameters are compatible with struc require(_avatarType == uint256(uint32(_avatarType))); require(_level == uint256(uint32(_level))); require(_experience == uint256(uint32(_experience))); // create object CryptoAvatar memory _avatar = CryptoAvatar({ statistics: _statistics, avatarType: uint32(_avatarType), level: uint32(_level), experience: uint32(_experience), creationTime: uint64(now), isHibernated: false }); // new index (push returns new array length) uint256 newAvatarId = avatars.push(_avatar) - 1; // emit creation event emit Creation(newAvatarId, _statistics, uint256(_avatarType), uint256(_level), uint256(_experience)); // Create avatar, assign to owner and emit the Transfer event _mint(_owner, newAvatarId); } /// @dev An external method that modifies the avatar characteristic. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate a Evolution event. /// Only whitelisted callers can access this /// @param _id The avatar id /// @param _statistics The avatar statistics. /// @param _avatarType The avatar type /// @param _level The avatar level /// @param _experience The avatar experience. function evolveCryptoAvatar( uint256 _id, uint256 _statistics, uint256 _avatarType, uint256 _level, uint256 _experience ) onlyWhitelisted external { // check if parameters are compatible with struct require(_avatarType == uint256(uint32(_avatarType))); require(_level == uint256(uint32(_level))); require(_experience == uint256(uint32(_experience))); // check if avatar exists require(exists(_id)); // retrieve avatar CryptoAvatar storage avatar = avatars[_id]; // check if avatar is hibernated and cannot be modified require(!avatar.isHibernated); // store new values avatar.statistics = _statistics; avatar.avatarType = uint32(_avatarType); avatar.level = uint32(_level); avatar.experience = uint32(_experience); // emit event emit Evolution(_id, _statistics, uint256(_avatarType), uint256(_level), uint256(_experience)); } /// @dev Set the avatar URI /// @param _tokenId The avatar id /// @param _uri The avatar URI function setTokenURI( uint256 _tokenId, string _uri ) onlyWhitelisted public { super._setTokenURI(_tokenId, _uri); } /// @dev Hibernate the avatar: cannot be modified /// @param _tokenId The avatar id function hibernate( uint256 _tokenId ) external { // check if avatar exists require(exists(_tokenId)); // retrieve avatar CryptoAvatar storage avatar = avatars[_tokenId]; // check if not already hibernated require(!avatar.isHibernated); // check if owner address owner = ownerOf(_tokenId); require(msg.sender == owner); // hibernate avatar.isHibernated = true; emit Hibernated(_tokenId); } /// @dev Wake up the avatar: can be modified /// @param _tokenId The avatar id function wakeUp( uint256 _tokenId ) external { // check if avatar exists require(exists(_tokenId)); // retrieve avatar CryptoAvatar storage avatar = avatars[_tokenId]; // check if not already hibernated require(avatar.isHibernated); // check if owner address owner = ownerOf(_tokenId); require(msg.sender == owner); // hibernate avatar.isHibernated = false; emit WokenUp(_tokenId); } }
check if avatar exists retrieve avatar check if not already hibernated check if owner hibernate
function wakeUp( uint256 _tokenId ) external { require(exists(_tokenId)); CryptoAvatar storage avatar = avatars[_tokenId]; require(avatar.isHibernated); address owner = ownerOf(_tokenId); require(msg.sender == owner); avatar.isHibernated = false; emit WokenUp(_tokenId); }
947,379
pragma solidity ^0.4.18; import "../node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "../node_modules/zeppelin-solidity/contracts/ownership/Ownable.sol"; /* UbiatarCoin token contract. */ contract UAC is StandardToken, Ownable { // SafeMath standard lib using SafeMath for uint; // Fields: string public constant name = "Ubiatar Coin"; string public constant symbol = "UAC"; uint public constant decimals = 18; // ICO contract address address public icoContractAddress = 0x0; // Bool to lock UAC transfers before ICO end bool public lockTransfers = true; // total UAC token supply uint public constant TOTAL_TOKEN_SUPPLY = 100000000 * 1 ether; // total ICO token supply uint public constant TOTAL_ICO_SUPPLY = 15000000 * 1 ether; // total presale token supply uint public constant TOTAL_PRESALE_SUPPLY = 17584778551358900100698693; // total advisors supply uint public constant TOTAL_ADVISORS_SUPPLY = 4915221448641099899301307; // total ubiatarPlay supply uint public constant TOTAL_UBIATARPLAY_SUPPLY = 50500000 * 1 ether; // total founders supply uint public constant TOTAL_FOUNDERS_SUPPLY = 12000000 * 1 ether; /// Modifiers: // Enable use only by ICO contract modifier byIcoContract() { require(msg.sender == icoContractAddress); _; } /// Setters/Getters // This function sets the ICO contract address function setIcoContractAddress(address _icoContractAddress) public onlyOwner { icoContractAddress = _icoContractAddress; } /// Functions: // UAC Constructor function UAC() public { require(TOTAL_TOKEN_SUPPLY == 100000000 * 1 ether); require(TOTAL_ICO_SUPPLY.add(TOTAL_PRESALE_SUPPLY).add(TOTAL_ADVISORS_SUPPLY).add(TOTAL_UBIATARPLAY_SUPPLY).add(TOTAL_FOUNDERS_SUPPLY) == TOTAL_TOKEN_SUPPLY); } /// @dev Override function transfer(address _to, uint256 _value) public returns(bool) { require(!lockTransfers); return super.transfer(_to,_value); } /// @dev Override function transferFrom(address _from, address _to, uint256 _value) public returns(bool) { require(!lockTransfers); return super.transferFrom(_from,_to,_value); } // It creates new token and it can be called only by ICO contract function issueTokens(address _who, uint _tokens) public byIcoContract { require((totalSupply_ + _tokens) <= TOTAL_TOKEN_SUPPLY); balances[_who] = balances[_who].add(_tokens); totalSupply_ = totalSupply_.add(_tokens); Transfer(0x0, _who, _tokens); } // It enables or disables token transfers function lockTransfer(bool _lock) public byIcoContract { lockTransfers = _lock; } // It disallows to send money directly to this contract function() public { revert(); } }
It creates new token and it can be called only by ICO contract
function issueTokens(address _who, uint _tokens) public byIcoContract { require((totalSupply_ + _tokens) <= TOTAL_TOKEN_SUPPLY); balances[_who] = balances[_who].add(_tokens); totalSupply_ = totalSupply_.add(_tokens); Transfer(0x0, _who, _tokens); }
6,425,886
./partial_match/1/0x3f669AeFF1607F8a0233CB2dE7508F5a9A114685/sources/BaseRegistrarImplementation.sol
Register a name. id The token ID (keccak256 of the label). owner The address that should own the registration. duration Duration in seconds for the registration./
function register(uint256 id, address owner, uint duration) external returns(uint) { return _register(id, owner, duration, true); }
3,712,815
pragma solidity >=0.4.21 <0.6.0; import "./algorithms/BytesUtils.sol"; import "./algorithms/RSA.sol"; import "./algorithms/ED25519.sol"; import "./algorithms/SHA1.sol"; import "./algorithms/SHA512.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; contract DkimChecker is Ownable, RSA, ED25519, SHA1, SHA512 { using BytesUtils for *; // ----------------------------------------------------------------------------------------------------// // ----------------------------------------------------------------------------------------------------// struct KeyRsa { bytes exponent; bytes modulus; } struct KeyEd { uint x; uint y; uint p; } address public oracle; // to be set to the oracle contract address for access restrictions mapping(bytes32 => mapping(bytes32 => KeyRsa)) public dkimKeysRsa; // domain name => selector => key mapping(bytes32 => mapping(bytes32 => KeyEd)) public dkimKeysEd; // domain name => selector => bytes(key) // ----------------------------------------------------------------------------------------------------// // ----------------------------------------------------------------------------------------------------// constructor(address _oracle) public { oracle =_oracle; } // Should be used with all function involving the oracle interaction, for access restrictions modifier onlyOracle() { if(msg.sender != oracle) revert("The msg.sender is different than the oracle address"); _; } // ----------------------------------------------------------------------------------------------------// // ----------------------------------------------------------------------------------------------------// // Dkim key setter function to be used by the oracle to save the public key components on-chain //_selector and _domain should be used to access the key saved onchain since they are necessary to resolve // TXT record they dns function setDkimKeyRsa(string memory _selector, string memory _domain, bytes memory _exponent, bytes memory _modulus) public onlyOracle returns(bool){ // Extra requirements can be added here to avoid issue with domainkey dns record update KeyRsa storage key = dkimKeysRsa[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; key.exponent = _exponent; key.modulus = _modulus; return true; } function setDkimKeyEd(string memory _selector, string memory _domain, uint x, uint y, uint p) public onlyOracle returns(bool){ // Extra requirements can be added here to avoid issue with domainkey dns record update KeyEd storage key = dkimKeysEd[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))] ; key.x = x; key.y = y; key.p = p; return true; } function getDkimKeyRsa(string memory _selector, string memory _domain) public view returns (bytes memory,bytes memory) { KeyRsa memory key = dkimKeysRsa[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; return (key.exponent,key.modulus); } function getDkimKeyEd(string memory _selector, string memory _domain) public view returns (uint x, uint y) { KeyEd memory key = dkimKeysEd[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; return (key.x,key.y); } // ----------------------------------------------------------------------------------------------------// // ----------------------------------------------------------------------------------------------------// event ReturnVal(bool); // If any valuable information contained inside the body of the emain needs to be used checkBody function // should be added to the verification step to avoid any exploit function checkBodySHA1(bytes memory body, bytes20 bodyHash) public returns (bool){ bytes20 computed = sha1(body); emit ReturnVal(bodyHash == computed); // just added to simulate a non-view function return true; } function checkBodySHA256(bytes memory body, bytes32 bodyHash) public returns (bool){ bytes32 computed = sha256(body); emit ReturnVal(bodyHash == computed); // just added to simulate a non-view function return true; } // ----------------------------------------------------------------------------------------------------// // ----------------------------------------------------------------------------------------------------// // _canonicalizedHeader is the header preprocessed and canonicalized all information can be extracted on-chain from from it function verifyRSASHA256(string memory _selector, string memory _domain, bytes memory _sig, bytes memory _canonicalizedHeader) public returns (bool) { // Recover the message from the signature KeyRsa memory key = dkimKeysRsa[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; bool ok; bytes memory result; (ok, result) = modexp(_sig, key.exponent, key.modulus); bool bl = ( ok && sha256(_canonicalizedHeader) == result.readBytes32(result.length - 32) ); emit ReturnVal(bl); // just added to simulate a non-view function return bl; } // _canonicalizedHeader is the header preprocessed and canonicalized all information can be extracted on-chain from from it function verifyRSASHA1(string memory _selector, string memory _domain,bytes memory _sig, bytes memory _canonicalizedHeader) public returns (bool) { KeyRsa memory key = dkimKeysRsa[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; bool ok; bytes memory result; (ok, result) = modexp(_sig, key.exponent, key.modulus); bool bl = (ok && sha1(_canonicalizedHeader) == result.readBytes20(result.length - 20) ); emit ReturnVal(bl); // just added to simulate a non-view function return bl; } // For more details abt ed25519 verification function check https://tools.ietf.org/html/rfc8032#section-5.1 // _r,_R and "_s" are the signature component. // _canonicalizedHeader is the header preprocessed and canonicalized all information can be extracted on-chain from from it function verifyED25519 ( string memory _selector, string memory _domain, uint _r, uint[2] memory _R, uint[2] memory _lhs , bytes memory _canonicalizedHeader ) public returns (bool) { KeyEd memory key = dkimKeysEd[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; uint[2] memory rhs; uint hash_512_mod_l = sha512modl(_r, key.p, uint256(sha256(_canonicalizedHeader))); (rhs[0], rhs[1]) = scalarMult([key.x , key.y], hash_512_mod_l); uint[2] memory Rs = ecAddVec(_R,rhs); bool bl = (_lhs[0] == Rs[0] && _lhs[1] == Rs[1]); emit ReturnVal(bl); // just added to simulate a non-view function return bl; } }
Recover the message from the signature
function verifyRSASHA256(string memory _selector, string memory _domain, bytes memory _sig, bytes memory _canonicalizedHeader) public returns (bool) { KeyRsa memory key = dkimKeysRsa[keccak256(abi.encodePacked(_selector))][keccak256(abi.encodePacked(_domain))]; bool ok; bytes memory result; (ok, result) = modexp(_sig, key.exponent, key.modulus); bool bl = ( ok && sha256(_canonicalizedHeader) == result.readBytes32(result.length - 32) ); return bl; }
13,127,750
./full_match/80001/0x866E8DEcA73BD1Fd2bEA37F86ba4B8c6C373b7e2/sources/contracts/TokenforNFT.sol
- to purchase the NFT by any user for the amount greater than the salePrice
function purchaseNFT() external payable { require(saleStarted, "Not for sale!"); require(msg.value >= salePrice, "Not enough amount sent"); collectionAddress.transferFrom(address(this), msg.sender, tokenId); saleStarted = false; canRedeem = true; emit NFTsold(msg.value, msg.sender); }
5,671,904
//SPDX-License-Identifier: MIT // shoutoutskwidkkxkkOxc,...;c::;;;,,,''',,;cdkkkkxxxxxdddddddd // xxxxxxxxxxxxxkkxxol;. ...........'........:xkkkxxxxxxxxxxxx // kkkkxxxxxxxdoc;,'.......''..........'...''..;dkkxxdddooooood // kkkkkkkkxl;'....''...'''...',,,;;:ccc;...'...,:;,,'''......; // OOOkkkkl,...''.''....''''..;oc:::;'......... ..........,:ld // OOOOOkl'.''''''''...'''''.............. ............';cloxOO // kkOOOk:..''''''''...''''''......... .......';:cc::ccc;':dOO // kkkkOk:..''''''''....''''.... ...',;:c::clodkkl;clloxkkk // kkkkkkc..'''''''''........ ...',;:lodxxkkkkkxol:,::,;dkOkkkk // xkkkkko'.'''.'...........;cooddddddooodxkkkkkkkxc;lddxkkkkkk // xxkkkkx;...',,;;'':lc::;'cxkdooooododoodkkkkkkkkx::xOOkkkkkx // xkkkkkd:;ldxkkOd:lkkkkxdodxkxolldxkkkxolccodxxxxxd:ckOkkkkxx // kkkkdccokOOOOOOc:dxkkkkkkxo:',cokkkkkkko. ....'cdl;oOkkkkkx // kdlccokOOOOOOOk::olddooc,.. .;xkkkkkkxoc,. ,xx:ckOkkkkk // c,,:llccxOOOO0d:cocloddl:. .okkkkkkkdc'. ,odl;dOOOkkk // xdoooc,:kOxllxo;ldloxxdl,. .lkkxdood:. ,:::llod:lOOOOOk // OOOkl''cc;,;;:;:xxollol'.,'....,okkkkxlod:.'lddddooxc:kOOOOO // kkdc:coodoloo;,okxoloddooddlcloloxxoooldkxddxkkkxdoxl:dOOOOO // kd:cxdoooodkxddkkkddxkkkkkkkxo:cldxdodxkkkkkkkkkkkkkl;okkkkk // xl;okxxkxllxkkkkkkkkkkkkkkkkkdoollc:::ldkkkkkkkkkkkkl;okkkkk // xo;cxxdooloxdxkkkkkkkkkkkkkkkxxl,. .:xkkkkkkkkkkc;okxxxx // xxo::clccll:ldkkkkkkkkkkkkkkx:'. ;dkkkkkkkkd::xxxxxx // xxxxocclc;,cxkkkkkkkkkkkkkkx:. .:kkkkkkkxc;oxxxxxx // xxxxkkxdxkl:lxkkkkkkkkkkkkko. ..,,'.';;,.:xkkkkxo::dkkxxxxd // xxxkkkkkOOkdc:lxkkkkkkkkkkko,';:cccccccccclxkxdlc:oxkkkxxxxd // xkkkkkOOOOOOkdc:cldxkkkkkkkxo:::cloooooolccccccldkOOkkkkkxxx // kkkkkOOOOkkkkkkxoccccclllloolc::ccllcccccccloxkkOOOOkkkkkkxx // kkkkkOOOkkkkkkxxxxxdolc::;;;;::;::cllodxxkkkkkkkkOOOOOkkkkkx // Ownership of this NFT grants full ownership and commercial usage rights of this NFT to the owner // All rights relinquished upon transfer. GG pragma solidity ^0.8.0; import "ERC721.sol"; import "Ownable.sol"; import "SafeMath.sol"; import "Counters.sol"; contract FuddersNFT is ERC721("Fudders", "NGMI"), Ownable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenSupply; modifier isTeam { require(isTeamMember[msg.sender]); _; } uint256 public constant MAX_PER_TX = 10; uint256 public constant MAX_SUPPLY = 6464; // NGMI uint256 public price = 32320000000000000; // 6464/2 fer da memes uint256 public REMAINING_RESERVED = 130; // 2% team allocation mapping(address => bool) public isTeamMember; bool public saleIsActive; string public baseTokenURI; address public constant addrOne = 0xF7aDD17E99F097f9D0A6150D093EC049B2698c60; address public constant addrTwo = 0x0B32b6a775cCF57ff75078a702249A65c8A581Fe; address public constant addrThree = 0x94e5149AC7B8B1249069f6D9DFCBb2590d641dDC; address public constant addrFour = 0x8958eBEB998DB0C051b4857aB8c1d758B12e423f; address public constant addrFive = 0x965891B44F8571545C9DeeB687970Bd53011C8d0; constructor() public { saleIsActive = false; setBaseURI("http://api.fudderverse.com/"); isTeamMember[addrOne] = true; isTeamMember[addrTwo] = true; isTeamMember[addrThree] = true; isTeamMember[addrFour] = true; isTeamMember[addrFive] = true; } //General mint function using counter instead of ERC721Enumerable's totalSupply() to reduce gas cost function mint(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require( numberOfTokens <= MAX_PER_TX, "Fudders: Max of 10 tokens per transaction" ); require( _tokenSupply.current().add(numberOfTokens) <= MAX_SUPPLY, "Fudders: Purchase would exceed max supply" ); require( price.mul(numberOfTokens) <= msg.value, "Fudders: Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfTokens; i++) { _tokenSupply.increment(); uint256 newTokenId = _tokenSupply.current(); _safeMint(msg.sender, newTokenId); } } //function for team token mint in batches of 10, team tokens are capped at 130 (2%) function teamMint() public isTeam { require( REMAINING_RESERVED >= 10, "Fudders: Insufficient reserves remaining" ); require(saleIsActive, "Fudders: Sale must be active to mint"); require( _tokenSupply.current().add(10) <= MAX_SUPPLY, "Fudders: Purchase would exceed max supply" ); REMAINING_RESERVED -= 10; for (uint256 i = 0; i < 10; i++) { _tokenSupply.increment(); uint256 newTokenId = _tokenSupply.current(); _safeMint(msg.sender, newTokenId); } } function _baseURI() internal virtual override view returns (string memory) { return baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { baseTokenURI = baseURI; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawSplit() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "Balance = 0"); _widthdraw(addrOne, balance.mul(10).div(100)); _widthdraw(addrTwo, balance.mul(25).div(100)); _widthdraw(addrThree, balance.mul(30).div(100)); _widthdraw(addrFour, address(this).balance); } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function changePrice(uint256 _price) public onlyOwner { price = _price; } function getPrice(uint256 _count) public view returns (uint256) { return price.mul(_count); } //If you are reading this, //message @DontCryWolf and let him know you love apples, //message @Velcrafting and let him know that it rains a lot in England, // and message @Metaverse_Yin "Hi from the future". //Sincerely, @0xFloop :) function totalSupply() external view returns (uint256) { return _tokenSupply.current(); } } // 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 "IERC721Metadata.sol"; import "Address.sol"; import "Context.sol"; import "Strings.sol"; import "ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _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 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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; } }
General mint function using counter instead of ERC721Enumerable's totalSupply() to reduce gas cost
function mint(uint256 numberOfTokens) public payable { require(saleIsActive, "Sale must be active to mint"); require( numberOfTokens <= MAX_PER_TX, "Fudders: Max of 10 tokens per transaction" ); require( _tokenSupply.current().add(numberOfTokens) <= MAX_SUPPLY, "Fudders: Purchase would exceed max supply" ); require( price.mul(numberOfTokens) <= msg.value, "Fudders: Ether value sent is not correct" ); for (uint256 i = 0; i < numberOfTokens; i++) { _tokenSupply.increment(); uint256 newTokenId = _tokenSupply.current(); _safeMint(msg.sender, newTokenId); } }
5,715,866
./partial_match/1/0xf7E781Cae2c2D8AC9Fe50023ecB8c93Cd65A9F90/sources/AggregatorProxy.sol
get the latest completed round where the answer was updated/
function latestRound() external view returns (uint256) { return aggregator.latestRound(); }
4,290,202
./partial_match/1313161554/0x7afd06811120462e86dbd41554445928C7AFBCAD/sources/contracts/distribution/PolarGenesisRewardPool.sol
Safe POLAR transfer function, just in case if rounding error causes pool to not have enough POLARs.
function safePolarTransfer(address _to, uint256 _amount) internal { uint256 _polarBalance = polar.balanceOf(address(this)); if (_polarBalance > 0) { if (_amount > _polarBalance) { polar.safeTransfer(_to, _polarBalance); polar.safeTransfer(_to, _amount); } } }
16,926,772
// 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); } /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll( address indexed account, address indexed operator, bool approved ); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev 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); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev 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); } } interface IGenArt { function getTokensByOwner(address owner) external view returns (uint256[] memory); function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address owner) external view returns (uint256); function isGoldToken(uint256 _tokenId) external view returns (bool); } /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract GenArtTokenAirdropPass is Context, Ownable, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; using Strings for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; mapping(uint256 => uint256) private _totalSupply; uint256[3] tokenIds = [1, 2, 3]; uint256[3] tokenId_prices = [0.5 ether, 2.25 ether, 10 ether]; uint256[3] tokenId_cap = [1875, 500, 25]; bool private _paused = false; address genArtMembershipAddress; uint256 endBlock; /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); /** * @dev See {_setURI}. */ constructor( address genArtMembershipAddress_, uint256 endBlock_, string memory uri_ ) { genArtMembershipAddress = genArtMembershipAddress_; endBlock = endBlock_; _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } function uri(uint256 _tokenId) external view virtual override returns (string memory) { return string(abi.encodePacked(_uri, _tokenId.toString())); } /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev Indicates weither any token exist with a given id, or not. */ function exists(uint256 id) public view virtual returns (bool) { return GenArtTokenAirdropPass.totalSupply(id) > 0; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require( account != address(0), "GenArtTokenAirdropPass: balance query for the zero address" ); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require( accounts.length == ids.length, "GenArtTokenAirdropPass: accounts and ids length mismatch" ); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function setPaused(bool _pause) public onlyOwner { _paused = _pause; if (_paused) { emit Paused(_msgSender()); } else { emit Unpaused(_msgSender()); } } function setUri(string memory newUri) public onlyOwner { _setURI(newUri); } function withdraw(uint256 value) public onlyOwner { address _owner = owner(); payable(_owner).transfer(value); } /** * @dev See {ERC1155-_mint}. */ function mint( uint256 membershipId, address account, uint256 id, uint256 amount ) public payable { require( block.number < endBlock, "GenArtTokenAirdropPass: mint pass sale ended" ); require( id == 1 || id == 2 || id == 3, "GenArtTokenAirdropPass: invalid token id" ); uint256 index = id - 1; require( _totalSupply[id] + amount <= tokenId_cap[index], "GenArtTokenAirdropPass: requested amount too high" ); require( IGenArt(genArtMembershipAddress).ownerOf(membershipId) == msg.sender, "GenArtTokenAirdropPass: sender is not owner of membership" ); uint256 ethValue; unchecked { ethValue = tokenId_prices[index] * amount; } require( ethValue <= msg.value, "GenArtTokenAirdropPass: wrong amount sent" ); _mint(account, id, amount, ""); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_burn}. */ function burn( address account, uint256 id, uint256 amount ) public { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "GenArtTokenAirdropPass: caller is not owner nor approved" ); _burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require( _msgSender() != operator, "GenArtTokenAirdropPass: setting approval status for self" ); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "GenArtTokenAirdropPass: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "GenArtTokenAirdropPass: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( to != address(0), "GenArtTokenAirdropPass: transfer to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); uint256 fromBalance = _balances[id][from]; require( fromBalance >= amount, "GenArtTokenAirdropPass: insufficient balance for transfer" ); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( ids.length == amounts.length, "GenArtTokenAirdropPass: ids and amounts length mismatch" ); require( to != address(0), "GenArtTokenAirdropPass: transfer to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require( fromBalance >= amount, "GenArtTokenAirdropPass: insufficient balance for transfer" ); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck( operator, from, to, ids, amounts, data ); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( account != address(0), "GenArtTokenAirdropPass: mint to the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); _balances[id][account] += amount; emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck( operator, address(0), account, id, amount, data ); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require( account != address(0), "GenArtTokenAirdropPass: burn from the zero address" ); address operator = _msgSender(); _beforeTokenTransfer(); uint256 accountBalance = _balances[id][account]; require( accountBalance >= amount, "GenArtTokenAirdropPass: burn amount exceeds balance" ); unchecked { _balances[id][account] = accountBalance - amount; } emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer() internal virtual { require(!paused(), "ERC1155Pausable: token transfer while paused"); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received( operator, from, id, amount, data ) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert( "GenArtTokenAirdropPass: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer" ); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived( operator, from, ids, amounts, data ) returns (bytes4 response) { if ( response != IERC1155Receiver.onERC1155BatchReceived.selector ) { revert( "GenArtTokenAirdropPass: ERC1155Receiver rejected tokens" ); } } catch Error(string memory reason) { revert(reason); } catch { revert( "GenArtTokenAirdropPass: transfer to non ERC1155Receiver implementer" ); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } }
See {IERC1155-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override { require( _msgSender() != operator, "GenArtTokenAirdropPass: setting approval status for self" ); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
11,994,837
./full_match/4/0x8Ff4b4c84940092eee58BC3583dF417489B64F27/sources/browser/ERC1363PayableCrowdsale.sol
return the address where funds are collected./
function wallet() public view returns (address) { return _wallet; }
12,367,984
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; // Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below). contract LiquidationWithdrawer { function withdrawLiquidation( address financialContractAddress, uint256 liquidationId, address sponsor ) public returns (FixedPoint.Unsigned memory) { return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor); } } interface IFinancialContract { function withdrawLiquidation(uint256 liquidationId, address sponsor) external returns (FixedPoint.Unsigned memory amountWithdrawn); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; /** * @title Library for fixed point arithmetic on uints */ library FixedPoint { using SafeMath for uint256; using SignedSafeMath for int256; // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For unsigned values: // This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77. uint256 private constant FP_SCALING_FACTOR = 10**18; // --------------------------------------- UNSIGNED ----------------------------------------------------------------------------- struct Unsigned { uint256 rawValue; } /** * @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a uint to convert into a FixedPoint. * @return the converted FixedPoint. */ function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) { return Unsigned(a.mul(FP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if equal, or False. */ function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if equal, or False. */ function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a > b`, or False. */ function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a > b`, or False. */ function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a < b`, or False. */ function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a < b`, or False. */ function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint. * @param b a uint256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledUint(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a uint256. * @param b a FixedPoint. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) { return fromUnscaledUint(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the minimum of `a` and `b`. */ function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint. * @param b a FixedPoint. * @return the maximum of `a` and `b`. */ function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the sum of `a` and `b`. */ function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return add(a, fromUnscaledUint(b)); } /** * @notice Subtracts two `Unsigned`s, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow. * @param a a FixedPoint. * @param b a uint256. * @return the difference of `a` and `b`. */ function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return sub(a, fromUnscaledUint(b)); } /** * @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow. * @param a a uint256. * @param b a FixedPoint. * @return the difference of `a` and `b`. */ function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return sub(fromUnscaledUint(a), b); } /** * @notice Multiplies two `Unsigned`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as a uint256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because FP_SCALING_FACTOR != 0. return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR); } /** * @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint. * @param b a uint256. * @return the product of `a` and `b`. */ function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.mul(b)); } /** * @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 mulRaw = a.rawValue.mul(b.rawValue); uint256 mulFloor = mulRaw / FP_SCALING_FACTOR; uint256 mod = mulRaw.mod(FP_SCALING_FACTOR); if (mod != 0) { return Unsigned(mulFloor.add(1)); } else { return Unsigned(mulFloor); } } /** * @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint. * @param b a FixedPoint. * @return the product of `a` and `b`. */ function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Unsigned(a.rawValue.mul(b)); } /** * @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as a uint256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { return Unsigned(a.rawValue.div(b)); } /** * @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a uint256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) { return div(fromUnscaledUint(a), b); } /** * @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) { uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR); uint256 divFloor = aScaled.div(b.rawValue); uint256 mod = aScaled.mod(b.rawValue); if (mod != 0) { return Unsigned(divFloor.add(1)); } else { return Unsigned(divFloor); } } /** * @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return the quotient of `a` divided by `b`. */ function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) { // Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))" // similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned. // This creates the possibility of overflow if b is very large. return divCeil(a, fromUnscaledUint(b)); } /** * @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint numerator. * @param b a uint256 denominator. * @return output is `a` to the power of `b`. */ function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) { output = fromUnscaledUint(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } // ------------------------------------------------- SIGNED ------------------------------------------------------------- // Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5". // For signed values: // This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76. int256 private constant SFP_SCALING_FACTOR = 10**18; struct Signed { int256 rawValue; } function fromSigned(Signed memory a) internal pure returns (Unsigned memory) { require(a.rawValue >= 0, "Negative value provided"); return Unsigned(uint256(a.rawValue)); } function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) { require(a.rawValue <= uint256(type(int256).max), "Unsigned too large"); return Signed(int256(a.rawValue)); } /** * @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`. * @param a int to convert into a FixedPoint.Signed. * @return the converted FixedPoint.Signed. */ function fromUnscaledInt(int256 a) internal pure returns (Signed memory) { return Signed(a.mul(SFP_SCALING_FACTOR)); } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a int256. * @return True if equal, or False. */ function isEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue == fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if equal, or False. */ function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue == b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue > b.rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a > b`, or False. */ function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue > fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a > b`, or False. */ function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue > b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue >= b.rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue >= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is greater than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a >= b`, or False. */ function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue >= b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue < b.rawValue; } /** * @notice Whether `a` is less than `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a < b`, or False. */ function isLessThan(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue < fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a < b`, or False. */ function isLessThan(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue < b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) { return a.rawValue <= b.rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a a FixedPoint.Signed. * @param b an int256. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) { return a.rawValue <= fromUnscaledInt(b).rawValue; } /** * @notice Whether `a` is less than or equal to `b`. * @param a an int256. * @param b a FixedPoint.Signed. * @return True if `a <= b`, or False. */ function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) { return fromUnscaledInt(a).rawValue <= b.rawValue; } /** * @notice The minimum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the minimum of `a` and `b`. */ function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue < b.rawValue ? a : b; } /** * @notice The maximum of `a` and `b`. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the maximum of `a` and `b`. */ function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return a.rawValue > b.rawValue ? a : b; } /** * @notice Adds two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the sum of `a` and `b`. */ function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.add(b.rawValue)); } /** * @notice Adds an `Signed` to an unscaled int, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the sum of `a` and `b`. */ function add(Signed memory a, int256 b) internal pure returns (Signed memory) { return add(a, fromUnscaledInt(b)); } /** * @notice Subtracts two `Signed`s, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) { return Signed(a.rawValue.sub(b.rawValue)); } /** * @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow. * @param a a FixedPoint.Signed. * @param b an int256. * @return the difference of `a` and `b`. */ function sub(Signed memory a, int256 b) internal pure returns (Signed memory) { return sub(a, fromUnscaledInt(b)); } /** * @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow. * @param a an int256. * @param b a FixedPoint.Signed. * @return the difference of `a` and `b`. */ function sub(int256 a, Signed memory b) internal pure returns (Signed memory) { return sub(fromUnscaledInt(a), b); } /** * @notice Multiplies two `Signed`s, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is // stored internally as an int256 ~10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which // would round to 3, but this computation produces the result 2. // No need to use SafeMath because SFP_SCALING_FACTOR != 0. return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR); } /** * @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow. * @dev This will "floor" the product. * @param a a FixedPoint.Signed. * @param b an int256. * @return the product of `a` and `b`. */ function mul(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.mul(b)); } /** * @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 mulRaw = a.rawValue.mul(b.rawValue); int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR; // Manual mod because SignedSafeMath doesn't support it. int256 mod = mulRaw % SFP_SCALING_FACTOR; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(mulTowardsZero.add(valueToAdd)); } else { return Signed(mulTowardsZero); } } /** * @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow. * @param a a FixedPoint.Signed. * @param b a FixedPoint.Signed. * @return the product of `a` and `b`. */ function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Since b is an int, there is no risk of truncation and we can just mul it normally return Signed(a.rawValue.mul(b)); } /** * @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) { // There are two caveats with this computation: // 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows. // 10^41 is stored internally as an int256 10^59. // 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which // would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666. return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue)); } /** * @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function div(Signed memory a, int256 b) internal pure returns (Signed memory) { return Signed(a.rawValue.div(b)); } /** * @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0. * @dev This will "floor" the quotient. * @param a an int256 numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function div(int256 a, Signed memory b) internal pure returns (Signed memory) { return div(fromUnscaledInt(a), b); } /** * @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b a FixedPoint denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) { int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR); int256 divTowardsZero = aScaled.div(b.rawValue); // Manual mod because SignedSafeMath doesn't support it. int256 mod = aScaled % b.rawValue; if (mod != 0) { bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0); int256 valueToAdd = isResultPositive ? int256(1) : int256(-1); return Signed(divTowardsZero.add(valueToAdd)); } else { return Signed(divTowardsZero); } } /** * @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0. * @param a a FixedPoint numerator. * @param b an int256 denominator. * @return the quotient of `a` divided by `b`. */ function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) { // Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))" // similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed. // This creates the possibility of overflow if b is very large. return divAwayFromZero(a, fromUnscaledInt(b)); } /** * @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`. * @dev This will "floor" the result. * @param a a FixedPoint.Signed. * @param b a uint256 (negative exponents are not allowed). * @return output is `a` to the power of `b`. */ function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) { output = fromUnscaledInt(1); for (uint256 i = 0; i < b; i = i.add(1)) { output = mul(output, a); } } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-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 Integer division of two signed integers truncating the quotient, reverts on division by zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Subtracts two signed integers, reverts on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Adds two signed integers, reverts on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/VotingInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data. abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run on the test network, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) internal { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return now; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "./VotingAncillaryInterface.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingInterface { struct PendingRequest { bytes32 identifier; uint256 time; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct Commitment { bytes32 identifier; uint256 time; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct Reveal { bytes32 identifier; uint256 time; int256 price; int256 salt; } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) external virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(Commitment[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(Reveal[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (VotingAncillaryInterface.PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() public { currentTime = now; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that voters must use to Vote on price request resolutions. */ abstract contract VotingAncillaryInterface { struct PendingRequestAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; } // Captures the necessary data for making a commitment. // Used as a parameter when making batch commitments. // Not used as a data structure for storage. struct CommitmentAncillary { bytes32 identifier; uint256 time; bytes ancillaryData; bytes32 hash; bytes encryptedVote; } // Captures the necessary data for revealing a vote. // Used as a parameter when making batch reveals. // Not used as a data structure for storage. struct RevealAncillary { bytes32 identifier; uint256 time; int256 price; bytes ancillaryData; int256 salt; } // Note: the phases must be in order. Meaning the first enum value must be the first phase, etc. // `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last. enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER } /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public virtual; /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is stored on chain. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public virtual; /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public virtual; /** * @notice snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times but each round will only every have one snapshot at the * time of calling `_freezeRoundVariables`. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external virtual; /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price is being voted on. * @param price voted on during the commit phase. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public virtual; /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more information on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public virtual; /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests `PendingRequest` array containing identifiers * and timestamps for all pending requests. */ function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory); /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view virtual returns (Phase); /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view virtual returns (uint256); /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the * call is done within the timeout threshold (not expired). * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public virtual returns (FixedPoint.Unsigned memory); // Voting Owner functions. /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external virtual; /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual; /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual; /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "./Registry.sol"; import "./ResultComputation.sol"; import "./VoteTiming.sol"; import "./VotingToken.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; /** * @title Voting system for Oracle. * @dev Handles receiving and resolving price requests via a commit-reveal voting scheme. */ contract Voting is Testable, Ownable, OracleInterface, OracleAncillaryInterface, // Interface to support ancillary data with price requests. VotingInterface, VotingAncillaryInterface // Interface to support ancillary data with voting rounds. { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using VoteTiming for VoteTiming.Data; using ResultComputation for ResultComputation.Data; /**************************************** * VOTING DATA STRUCTURES * ****************************************/ // Identifies a unique price request for which the Oracle will always return the same value. // Tracks ongoing votes as well as the result of the vote. struct PriceRequest { bytes32 identifier; uint256 time; // A map containing all votes for this price in various rounds. mapping(uint256 => VoteInstance) voteInstances; // If in the past, this was the voting round where this price was resolved. If current or the upcoming round, // this is the voting round where this price will be voted on, but not necessarily resolved. uint256 lastVotingRound; // The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that // this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`. uint256 index; bytes ancillaryData; } struct VoteInstance { // Maps (voterAddress) to their submission. mapping(address => VoteSubmission) voteSubmissions; // The data structure containing the computed voting results. ResultComputation.Data resultComputation; } struct VoteSubmission { // A bytes32 of `0` indicates no commit or a commit that was already revealed. bytes32 commit; // The hash of the value that was revealed. // Note: this is only used for computation of rewards. bytes32 revealHash; } struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } /**************************************** * INTERNAL TRACKING * ****************************************/ // Maps round numbers to the rounds. mapping(uint256 => Round) public rounds; // Maps price request IDs to the PriceRequest struct. mapping(bytes32 => PriceRequest) private priceRequests; // Price request ids for price requests that haven't yet been marked as resolved. // These requests may be for future rounds. bytes32[] internal pendingPriceRequests; VoteTiming.Data public voteTiming; // Percentage of the total token supply that must be used in a vote to // create a valid price resolution. 1 == 100%. FixedPoint.Unsigned public gatPercentage; // Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that // should be split among the correct voters. // Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%. FixedPoint.Unsigned public inflationRate; // Time in seconds from the end of the round in which a price request is // resolved that voters can still claim their rewards. uint256 public rewardsExpirationTimeout; // Reference to the voting token. VotingToken public votingToken; // Reference to the Finder. FinderInterface private finder; // If non-zero, this contract has been migrated to this address. All voters and // financial contracts should query the new address only. address public migratedAddress; // Max value of an unsigned integer. uint256 private constant UINT_MAX = ~uint256(0); // Max length in bytes of ancillary data that can be appended to a price request. // As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily // comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to // storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function // well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here: // - https://etherscan.io/chart/gaslimit // - https://github.com/djrtwo/evm-opcode-gas-costs uint256 public constant ancillaryBytesLimit = 8192; bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot"))); /*************************************** * EVENTS * ****************************************/ event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); /** * @notice Construct the Voting contract. * @param _phaseLength length of the commit and reveal phases in seconds. * @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution. * @param _inflationRate percentage inflation per round used to increase token supply of correct voters. * @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed. * @param _votingToken address of the UMA token contract used to commit votes. * @param _finder keeps track of all contracts within the system based on their interfaceName. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Testable(_timerAddress) { voteTiming.init(_phaseLength); require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%"); gatPercentage = _gatPercentage; inflationRate = _inflationRate; votingToken = VotingToken(_votingToken); finder = FinderInterface(_finder); rewardsExpirationTimeout = _rewardsExpirationTimeout; } /*************************************** MODIFIERS ****************************************/ modifier onlyRegisteredContract() { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Caller must be migrated address"); } else { Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); require(registry.isContractRegistered(msg.sender), "Called must be registered"); } _; } modifier onlyIfNotMigrated() { require(migratedAddress == address(0), "Only call this if not migrated"); _; } /**************************************** * PRICE REQUEST AND ACCESS FUNCTIONS * ****************************************/ /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. The length of the ancillary data * is limited such that this method abides by the EVM transaction gas limit. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override onlyRegisteredContract() { uint256 blockTime = getCurrentTime(); require(time <= blockTime, "Can only request in past"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData); PriceRequest storage priceRequest = priceRequests[priceRequestId]; uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.NotRequested) { // Price has never been requested. // Price requests always go in the next round, so add 1 to the computed current round. uint256 nextRoundId = currentRoundId.add(1); priceRequests[priceRequestId] = PriceRequest({ identifier: identifier, time: time, lastVotingRound: nextRoundId, index: pendingPriceRequests.length, ancillaryData: ancillaryData }); pendingPriceRequests.push(priceRequestId); emit PriceRequestAdded(nextRoundId, identifier, time); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function requestPrice(bytes32 identifier, uint256 time) public override { requestPrice(identifier, time, ""); } /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (bool) { (bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData); return _hasPrice; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { return hasPrice(identifier, time, ""); } /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override onlyRegisteredContract() returns (int256) { (bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData); // If the price wasn't available, revert with the provided message. require(_hasPrice, message); return price; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { return getPrice(identifier, time, ""); } /** * @notice Gets the status of a list of price requests, identified by their identifier and time. * @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0. * @param requests array of type PendingRequest which includes an identifier and timestamp for each request. * @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests. */ function getPriceRequestStatuses(PendingRequestAncillary[] memory requests) public view returns (RequestState[] memory) { RequestState[] memory requestStates = new RequestState[](requests.length); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); for (uint256 i = 0; i < requests.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData); RequestStatus status = _getRequestStatus(priceRequest, currentRoundId); // If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated. if (status == RequestStatus.Active) { requestStates[i].lastVotingRound = currentRoundId; } else { requestStates[i].lastVotingRound = priceRequest.lastVotingRound; } requestStates[i].status = status; } return requestStates; } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) { PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length); for (uint256 i = 0; i < requests.length; i++) { requestsAncillary[i].identifier = requests[i].identifier; requestsAncillary[i].time = requests[i].time; requestsAncillary[i].ancillaryData = ""; } return getPriceRequestStatuses(requestsAncillary); } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Commit a vote for a price request for `identifier` at `time`. * @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase. * Commits can be changed. * @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior, * voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then * they can determine the vote pre-reveal. * @param identifier uniquely identifies the committed vote. EG BTC/USD price pair. * @param time unix timestamp of the price being voted on. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) public override onlyIfNotMigrated() { require(hash != bytes32(0), "Invalid provided hash"); // Current time is required for all vote timing queries. uint256 blockTime = getCurrentTime(); require( voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit, "Cannot commit in reveal phase" ); // At this point, the computed and last updated round ID should be equal. uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); require( _getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active, "Cannot commit inactive request" ); priceRequest.lastVotingRound = currentRoundId; VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId]; voteInstance.voteSubmissions[msg.sender].commit = hash; emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitVote( bytes32 identifier, uint256 time, bytes32 hash ) public override onlyIfNotMigrated() { commitVote(identifier, time, "", hash); } /** * @notice Snapshot the current round's token balances and lock in the inflation rate and GAT. * @dev This function can be called multiple times, but only the first call per round into this function or `revealVote` * will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period. * @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the * snapshot. */ function snapshotCurrentRound(bytes calldata signature) external override(VotingInterface, VotingAncillaryInterface) onlyIfNotMigrated() { uint256 blockTime = getCurrentTime(); require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase"); // Require public snapshot require signature to ensure caller is an EOA. require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender"); uint256 roundId = voteTiming.computeCurrentRoundId(blockTime); _freezeRoundVariables(roundId); } /** * @notice Reveal a previously committed vote for `identifier` at `time`. * @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash` * that `commitVote()` was called with. Only the committer can reveal their vote. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price voted on during the commit phase. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param salt value used to hide the commitment price during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) public override onlyIfNotMigrated() { require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase"); // Note: computing the current round is required to disallow people from revealing an old commit after the round is over. uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[roundId]; VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender]; // Scoping to get rid of a stack too deep error. { // 0 hashes are disallowed in the commit phase, so they indicate a different error. // Cannot reveal an uncommitted or previously revealed hash require(voteSubmission.commit != bytes32(0), "Invalid hash reveal"); require( keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) == voteSubmission.commit, "Revealed data != commit hash" ); // To protect against flash loans, we require snapshot be validated as EOA. require(rounds[roundId].snapshotId != 0, "Round has no snapshot"); } // Get the frozen snapshotId uint256 snapshotId = rounds[roundId].snapshotId; delete voteSubmission.commit; // Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId)); // Set the voter's submission. voteSubmission.revealHash = keccak256(abi.encode(price)); // Add vote to the results. voteInstance.resultComputation.addVote(price, balance); emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function revealVote( bytes32 identifier, uint256 time, int256 price, int256 salt ) public override { revealVote(identifier, time, price, "", salt); } /** * @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote * @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to * retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience. * @param identifier unique price pair identifier. Eg: BTC/USD price pair. * @param time unix timestamp of for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param hash keccak256 hash of the price you want to vote for and a `int256 salt`. * @param encryptedVote offchain encrypted blob containing the voters amount, time and salt. */ function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, ancillaryData, hash); uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime()); emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote); } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function commitAndEmitEncryptedVote( bytes32 identifier, uint256 time, bytes32 hash, bytes memory encryptedVote ) public override { commitVote(identifier, time, "", hash); commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote); } /** * @notice Submit a batch of commits in a single transaction. * @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event. * Look at `project-root/common/Constants.js` for the tested maximum number of * commitments that can fit in one transaction. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(CommitmentAncillary[] memory commits) public override { for (uint256 i = 0; i < commits.length; i++) { if (commits[i].encryptedVote.length == 0) { commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash); } else { commitAndEmitEncryptedVote( commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash, commits[i].encryptedVote ); } } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchCommit(Commitment[] memory commits) public override { CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length); for (uint256 i = 0; i < commits.length; i++) { commitsAncillary[i].identifier = commits[i].identifier; commitsAncillary[i].time = commits[i].time; commitsAncillary[i].ancillaryData = ""; commitsAncillary[i].hash = commits[i].hash; commitsAncillary[i].encryptedVote = commits[i].encryptedVote; } batchCommit(commitsAncillary); } /** * @notice Reveal multiple votes in a single transaction. * Look at `project-root/common/Constants.js` for the tested maximum number of reveals. * that can fit in one transaction. * @dev For more info on reveals, review the comment for `revealVote`. * @param reveals array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(RevealAncillary[] memory reveals) public override { for (uint256 i = 0; i < reveals.length; i++) { revealVote( reveals[i].identifier, reveals[i].time, reveals[i].price, reveals[i].ancillaryData, reveals[i].salt ); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function batchReveal(Reveal[] memory reveals) public override { RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length); for (uint256 i = 0; i < reveals.length; i++) { revealsAncillary[i].identifier = reveals[i].identifier; revealsAncillary[i].time = reveals[i].time; revealsAncillary[i].price = reveals[i].price; revealsAncillary[i].ancillaryData = ""; revealsAncillary[i].salt = reveals[i].salt; } batchReveal(revealsAncillary); } /** * @notice Retrieves rewards owed for a set of resolved price requests. * @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold * (not expired). Note that a named return value is used here to avoid a stack to deep error. * @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller. * @param roundId the round from which voting rewards will be retrieved from. * @param toRetrieve array of PendingRequests which rewards are retrieved from. * @return totalRewardToIssue total amount of rewards returned to the voter. */ function retrieveRewards( address voterAddress, uint256 roundId, PendingRequestAncillary[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) { if (migratedAddress != address(0)) { require(msg.sender == migratedAddress, "Can only call from migrated"); } require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId"); Round storage round = rounds[roundId]; bool isExpired = getCurrentTime() > round.rewardsExpirationTime; FixedPoint.Unsigned memory snapshotBalance = FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId)); // Compute the total amount of reward that will be issued for each of the votes in the round. FixedPoint.Unsigned memory snapshotTotalSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId)); FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply); // Keep track of the voter's accumulated token reward. totalRewardToIssue = FixedPoint.Unsigned(0); for (uint256 i = 0; i < toRetrieve.length; i++) { PriceRequest storage priceRequest = _getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData); VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; // Only retrieve rewards for votes resolved in same round require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round"); _resolvePriceRequest(priceRequest, voteInstance); if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) { continue; } else if (isExpired) { // Emit a 0 token retrieval on expired rewards. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } else if ( voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash) ) { // The price was successfully resolved during the voter's last voting round, the voter revealed // and was correct, so they are eligible for a reward. // Compute the reward and add to the cumulative reward. FixedPoint.Unsigned memory reward = snapshotBalance.mul(totalRewardPerVote).div( voteInstance.resultComputation.getTotalCorrectlyVotedTokens() ); totalRewardToIssue = totalRewardToIssue.add(reward); // Emit reward retrieval for this vote. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, reward.rawValue ); } else { // Emit a 0 token retrieval on incorrect votes. emit RewardsRetrieved( voterAddress, roundId, toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData, 0 ); } // Delete the submission to capture any refund and clean up storage. delete voteInstance.voteSubmissions[voterAddress].revealHash; } // Issue any accumulated rewards. if (totalRewardToIssue.isGreaterThan(0)) { require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed"); } } // Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version. function retrieveRewards( address voterAddress, uint256 roundId, PendingRequest[] memory toRetrieve ) public override returns (FixedPoint.Unsigned memory) { PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length); for (uint256 i = 0; i < toRetrieve.length; i++) { toRetrieveAncillary[i].identifier = toRetrieve[i].identifier; toRetrieveAncillary[i].time = toRetrieve[i].time; toRetrieveAncillary[i].ancillaryData = ""; } return retrieveRewards(voterAddress, roundId, toRetrieveAncillary); } /**************************************** * VOTING GETTER FUNCTIONS * ****************************************/ /** * @notice Gets the queries that are being voted on this round. * @return pendingRequests array containing identifiers of type `PendingRequest`. * and timestamps for all pending requests. */ function getPendingRequests() external view override(VotingInterface, VotingAncillaryInterface) returns (PendingRequestAncillary[] memory) { uint256 blockTime = getCurrentTime(); uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime); // Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter // `pendingPriceRequests` only to those requests that have an Active RequestStatus. PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length); uint256 numUnresolved = 0; for (uint256 i = 0; i < pendingPriceRequests.length; i++) { PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]]; if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) { unresolved[numUnresolved] = PendingRequestAncillary({ identifier: priceRequest.identifier, time: priceRequest.time, ancillaryData: priceRequest.ancillaryData }); numUnresolved++; } } PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved); for (uint256 i = 0; i < numUnresolved; i++) { pendingRequests[i] = unresolved[i]; } return pendingRequests; } /** * @notice Returns the current voting phase, as a function of the current time. * @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }. */ function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) { return voteTiming.computeCurrentPhase(getCurrentTime()); } /** * @notice Returns the current round ID, as a function of the current time. * @return uint256 representing the unique round ID. */ function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) { return voteTiming.computeCurrentRoundId(getCurrentTime()); } /**************************************** * OWNER ADMIN FUNCTIONS * ****************************************/ /** * @notice Disables this Voting contract in favor of the migrated one. * @dev Can only be called by the contract owner. * @param newVotingAddress the newly migrated contract address. */ function setMigrated(address newVotingAddress) external override(VotingInterface, VotingAncillaryInterface) onlyOwner { migratedAddress = newVotingAddress; } /** * @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newInflationRate sets the next round's inflation rate. */ function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { inflationRate = newInflationRate; } /** * @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun. * @dev This method is public because calldata structs are not currently supported by solidity. * @param newGatPercentage sets the next round's Gat percentage. */ function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%"); gatPercentage = newGatPercentage; } /** * @notice Resets the rewards expiration timeout. * @dev This change only applies to rounds that have not yet begun. * @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards. */ function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public override(VotingInterface, VotingAncillaryInterface) onlyOwner { rewardsExpirationTimeout = NewRewardsExpirationTimeout; } /**************************************** * PRIVATE AND INTERNAL FUNCTIONS * ****************************************/ // Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent // the resolved price and a string which is filled with an error message, if there was an error or "". function _getPriceOrError( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns ( bool, int256, string memory ) { PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData); uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime()); RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId); if (requestStatus == RequestStatus.Active) { return (false, 0, "Current voting round not ended"); } else if (requestStatus == RequestStatus.Resolved) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return (true, resolvedPrice, ""); } else if (requestStatus == RequestStatus.Future) { return (false, 0, "Price is still to be voted on"); } else { return (false, 0, "Price was never requested"); } } function _getPriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private view returns (PriceRequest storage) { return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)]; } function _encodePriceRequest( bytes32 identifier, uint256 time, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encode(identifier, time, ancillaryData)); } function _freezeRoundVariables(uint256 roundId) private { Round storage round = rounds[roundId]; // Only on the first reveal should the snapshot be captured for that round. if (round.snapshotId == 0) { // There is no snapshot ID set, so create one. round.snapshotId = votingToken.snapshot(); // Set the round inflation rate to the current global inflation rate. rounds[roundId].inflationRate = inflationRate; // Set the round gat percentage to the current global gat rate. rounds[roundId].gatPercentage = gatPercentage; // Set the rewards expiration time based on end of time of this round and the current global timeout. rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add( rewardsExpirationTimeout ); } } function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private { if (priceRequest.index == UINT_MAX) { return; } (bool isResolved, int256 resolvedPrice) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); require(isResolved, "Can't resolve unresolved request"); // Delete the resolved price request from pendingPriceRequests. uint256 lastIndex = pendingPriceRequests.length - 1; PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]]; lastPriceRequest.index = priceRequest.index; pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex]; pendingPriceRequests.pop(); priceRequest.index = UINT_MAX; emit PriceResolved( priceRequest.lastVotingRound, priceRequest.identifier, priceRequest.time, resolvedPrice, priceRequest.ancillaryData ); } function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) { uint256 snapshotId = rounds[roundId].snapshotId; if (snapshotId == 0) { // No snapshot - return max value to err on the side of caution. return FixedPoint.Unsigned(UINT_MAX); } // Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly // initialize the Unsigned value with the returned uint. FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId)); // Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens. return snapshottedSupply.mul(rounds[roundId].gatPercentage); } function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId) private view returns (RequestStatus) { if (priceRequest.lastVotingRound == 0) { return RequestStatus.NotRequested; } else if (priceRequest.lastVotingRound < currentRoundId) { VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound]; (bool isResolved, ) = voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound)); return isResolved ? RequestStatus.Resolved : RequestStatus.Active; } else if (priceRequest.lastVotingRound == currentRoundId) { return RequestStatus.Active; } else { // Means than priceRequest.lastVotingRound > currentRoundId return RequestStatus.Future; } } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleAncillaryInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @param time unix timestamp for the price request. */ function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view virtual returns (int256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../interfaces/RegistryInterface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title Registry for financial contracts and approved financial contract creators. * @dev Maintains a whitelist of financial contract creators that are allowed * to register new financial contracts and stores party members of a financial contract. */ contract Registry is RegistryInterface, MultiRole { using SafeMath for uint256; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // The owner manages the set of ContractCreators. ContractCreator // Can register financial contracts. } // This enum is required because a `WasValid` state is required // to ensure that financial contracts cannot be re-registered. enum Validity { Invalid, Valid } // Local information about a contract. struct FinancialContract { Validity valid; uint128 index; } struct Party { address[] contracts; // Each financial contract address is stored in this array. // The address of each financial contract is mapped to its index for constant time look up and deletion. mapping(address => uint256) contractIndex; } // Array of all contracts that are approved to use the UMA Oracle. address[] public registeredContracts; // Map of financial contract contracts to the associated FinancialContract struct. mapping(address => FinancialContract) public contractMap; // Map each party member to their their associated Party struct. mapping(address => Party) private partyMap; /**************************************** * EVENTS * ****************************************/ event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties); event PartyAdded(address indexed contractAddress, address indexed party); event PartyRemoved(address indexed contractAddress, address indexed party); /** * @notice Construct the Registry contract. */ constructor() public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); // Start with no contract creators registered. _createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0)); } /**************************************** * REGISTRATION FUNCTIONS * ****************************************/ /** * @notice Registers a new financial contract. * @dev Only authorized contract creators can call this method. * @param parties array of addresses who become parties in the contract. * @param contractAddress address of the contract against which the parties are registered. */ function registerContract(address[] calldata parties, address contractAddress) external override onlyRoleHolder(uint256(Roles.ContractCreator)) { FinancialContract storage financialContract = contractMap[contractAddress]; require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once"); // Store contract address as a registered contract. registeredContracts.push(contractAddress); // No length check necessary because we should never hit (2^127 - 1) contracts. financialContract.index = uint128(registeredContracts.length.sub(1)); // For all parties in the array add them to the contract's parties. financialContract.valid = Validity.Valid; for (uint256 i = 0; i < parties.length; i = i.add(1)) { _addPartyToContract(parties[i], contractAddress); } emit NewContractRegistered(contractAddress, msg.sender, parties); } /** * @notice Adds a party member to the calling contract. * @dev msg.sender will be used to determine the contract that this party is added to. * @param party new party for the calling contract. */ function addPartyToContract(address party) external override { address contractAddress = msg.sender; require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract"); _addPartyToContract(party, contractAddress); } /** * @notice Removes a party member from the calling contract. * @dev msg.sender will be used to determine the contract that this party is removed from. * @param partyAddress address to be removed from the calling contract. */ function removePartyFromContract(address partyAddress) external override { address contractAddress = msg.sender; Party storage party = partyMap[partyAddress]; uint256 numberOfContracts = party.contracts.length; require(numberOfContracts != 0, "Party has no contracts"); require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract"); require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party"); // Index of the current location of the contract to remove. uint256 deleteIndex = party.contractIndex[contractAddress]; // Store the last contract's address to update the lookup map. address lastContractAddress = party.contracts[numberOfContracts - 1]; // Swap the contract to be removed with the last contract. party.contracts[deleteIndex] = lastContractAddress; // Update the lookup index with the new location. party.contractIndex[lastContractAddress] = deleteIndex; // Pop the last contract from the array and update the lookup map. party.contracts.pop(); delete party.contractIndex[contractAddress]; emit PartyRemoved(contractAddress, partyAddress); } /**************************************** * REGISTRY STATE GETTERS * ****************************************/ /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the financial contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view override returns (bool) { return contractMap[contractAddress].valid == Validity.Valid; } /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view override returns (address[] memory) { return partyMap[party].contracts; } /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view override returns (address[] memory) { return registeredContracts; } /** * @notice checks if an address is a party of a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) { uint256 index = partyMap[party].contractIndex[contractAddress]; return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _addPartyToContract(address party, address contractAddress) internal { require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once"); uint256 contractIndex = partyMap[party].contracts.length; partyMap[party].contracts.push(contractAddress); partyMap[party].contractIndex[contractAddress] = contractIndex; emit PartyAdded(contractAddress, party); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/FixedPoint.sol"; /** * @title Computes vote results. * @dev The result is the mode of the added votes. Otherwise, the vote is unresolved. */ library ResultComputation { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL LIBRARY DATA STRUCTURE * ****************************************/ struct Data { // Maps price to number of tokens that voted for that price. mapping(int256 => FixedPoint.Unsigned) voteFrequency; // The total votes that have been added. FixedPoint.Unsigned totalVotes; // The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`. int256 currentMode; } /**************************************** * VOTING FUNCTIONS * ****************************************/ /** * @notice Adds a new vote to be used when computing the result. * @param data contains information to which the vote is applied. * @param votePrice value specified in the vote for the given `numberTokens`. * @param numberTokens number of tokens that voted on the `votePrice`. */ function addVote( Data storage data, int256 votePrice, FixedPoint.Unsigned memory numberTokens ) internal { data.totalVotes = data.totalVotes.add(numberTokens); data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens); if ( votePrice != data.currentMode && data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode]) ) { data.currentMode = votePrice; } } /**************************************** * VOTING STATE GETTERS * ****************************************/ /** * @notice Returns whether the result is resolved, and if so, what value it resolved to. * @dev `price` should be ignored if `isResolved` is false. * @param data contains information against which the `minVoteThreshold` is applied. * @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be * used to enforce a minimum voter participation rate, regardless of how the votes are distributed. * @return isResolved indicates if the price has been resolved correctly. * @return price the price that the dvm resolved to. */ function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold) internal view returns (bool isResolved, int256 price) { FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100); if ( data.totalVotes.isGreaterThan(minVoteThreshold) && data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold) ) { // `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price. isResolved = true; price = data.currentMode; } else { isResolved = false; } } /** * @notice Checks whether a `voteHash` is considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains information against which the `voteHash` is checked. * @param voteHash committed hash submitted by the voter. * @return bool true if the vote was correct. */ function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) { return voteHash == keccak256(abi.encode(data.currentMode)); } /** * @notice Gets the total number of tokens whose votes are considered correct. * @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`. * @param data contains all votes against which the correctly voted tokens are counted. * @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens. */ function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) { return data.voteFrequency[data.currentMode]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/VotingInterface.sol"; /** * @title Library to compute rounds and phases for an equal length commit-reveal voting cycle. */ library VoteTiming { using SafeMath for uint256; struct Data { uint256 phaseLength; } /** * @notice Initializes the data object. Sets the phase length based on the input. */ function init(Data storage data, uint256 phaseLength) internal { // This should have a require message but this results in an internal Solidity error. require(phaseLength > 0); data.phaseLength = phaseLength; } /** * @notice Computes the roundID based off the current time as floor(timestamp/roundLength). * @dev The round ID depends on the global timestamp but not on the lifetime of the system. * The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return roundId defined as a function of the currentTime and `phaseLength` from `data`. */ function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return currentTime.div(roundLength); } /** * @notice compute the round end time as a function of the round Id. * @param data input data object. * @param roundId uniquely identifies the current round. * @return timestamp unix time of when the current round will end. */ function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) { uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)); return roundLength.mul(roundId.add(1)); } /** * @notice Computes the current phase based only on the current time. * @param data input data object. * @param currentTime input unix timestamp used to compute the current roundId. * @return current voting phase based on current time and vote phases configuration. */ function computeCurrentPhase(Data storage data, uint256 currentTime) internal view returns (VotingAncillaryInterface.Phase) { // This employs some hacky casting. We could make this an if-statement if we're worried about type safety. return VotingAncillaryInterface.Phase( currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol"; /** * @title Ownership of this token allows a voter to respond to price requests. * @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards. */ contract VotingToken is ExpandedERC20, ERC20Snapshot { /** * @notice Constructs the VotingToken. */ constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {} /** * @notice Creates a new snapshot ID. * @return uint256 Thew new snapshot ID. */ function snapshot() external returns (uint256) { return _snapshot(); } // _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot, // therefore the compiler will complain that VotingToken must override these methods // because the two base classes (ERC20 and ERC20Snapshot) both define the same functions function _transfer( address from, address to, uint256 value ) internal override(ERC20, ERC20Snapshot) { super._transfer(from, to, value); } function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._mint(account, value); } function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) { super._burn(account, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.6.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. * * 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: invalid signature length"); } // 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: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: 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), "ECDSA: invalid signature"); return signer; } /** * @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)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; library Exclusive { struct RoleMembership { address member; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.member == memberToCheck; } function resetMember(RoleMembership storage roleMembership, address newMember) internal { require(newMember != address(0x0), "Cannot set an exclusive role to 0x0"); roleMembership.member = newMember; } function getMember(RoleMembership storage roleMembership) internal view returns (address) { return roleMembership.member; } function init(RoleMembership storage roleMembership, address initialMember) internal { resetMember(roleMembership, initialMember); } } library Shared { struct RoleMembership { mapping(address => bool) members; } function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) { return roleMembership.members[memberToCheck]; } function addMember(RoleMembership storage roleMembership, address memberToAdd) internal { require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role"); roleMembership.members[memberToAdd] = true; } function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal { roleMembership.members[memberToRemove] = false; } function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal { for (uint256 i = 0; i < initialMembers.length; i++) { addMember(roleMembership, initialMembers[i]); } } } /** * @title Base class to manage permissions for the derived class. */ abstract contract MultiRole { using Exclusive for Exclusive.RoleMembership; using Shared for Shared.RoleMembership; enum RoleType { Invalid, Exclusive, Shared } struct Role { uint256 managingRole; RoleType roleType; Exclusive.RoleMembership exclusiveRoleMembership; Shared.RoleMembership sharedRoleMembership; } mapping(uint256 => Role) private roles; event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager); event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager); /** * @notice Reverts unless the caller is a member of the specified roleId. */ modifier onlyRoleHolder(uint256 roleId) { require(holdsRole(roleId, msg.sender), "Sender does not hold required role"); _; } /** * @notice Reverts unless the caller is a member of the manager role for the specified roleId. */ modifier onlyRoleManager(uint256 roleId) { require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager"); _; } /** * @notice Reverts unless the roleId represents an initialized, exclusive roleId. */ modifier onlyExclusive(uint256 roleId) { require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role"); _; } /** * @notice Reverts unless the roleId represents an initialized, shared roleId. */ modifier onlyShared(uint256 roleId) { require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role"); _; } /** * @notice Whether `memberToCheck` is a member of roleId. * @dev Reverts if roleId does not correspond to an initialized role. * @param roleId the Role to check. * @param memberToCheck the address to check. * @return True if `memberToCheck` is a member of `roleId`. */ function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) { Role storage role = roles[roleId]; if (role.roleType == RoleType.Exclusive) { return role.exclusiveRoleMembership.isMember(memberToCheck); } else if (role.roleType == RoleType.Shared) { return role.sharedRoleMembership.isMember(memberToCheck); } revert("Invalid roleId"); } /** * @notice Changes the exclusive role holder of `roleId` to `newMember`. * @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an * initialized, ExclusiveRole. * @param roleId the ExclusiveRole membership to modify. * @param newMember the new ExclusiveRole member. */ function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) { roles[roleId].exclusiveRoleMembership.resetMember(newMember); emit ResetExclusiveMember(roleId, newMember, msg.sender); } /** * @notice Gets the current holder of the exclusive role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, exclusive role. * @param roleId the ExclusiveRole membership to check. * @return the address of the current ExclusiveRole member. */ function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) { return roles[roleId].exclusiveRoleMembership.getMember(); } /** * @notice Adds `newMember` to the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param newMember the new SharedRole member. */ function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.addMember(newMember); emit AddedSharedMember(roleId, newMember, msg.sender); } /** * @notice Removes `memberToRemove` from the shared role, `roleId`. * @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the * managing role for `roleId`. * @param roleId the SharedRole membership to modify. * @param memberToRemove the current SharedRole member to remove. */ function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) { roles[roleId].sharedRoleMembership.removeMember(memberToRemove); emit RemovedSharedMember(roleId, memberToRemove, msg.sender); } /** * @notice Removes caller from the role, `roleId`. * @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an * initialized, SharedRole. * @param roleId the SharedRole membership to modify. */ function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) { roles[roleId].sharedRoleMembership.removeMember(msg.sender); emit RemovedSharedMember(roleId, msg.sender, msg.sender); } /** * @notice Reverts if `roleId` is not initialized. */ modifier onlyValidRole(uint256 roleId) { require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId"); _; } /** * @notice Reverts if `roleId` is initialized. */ modifier onlyInvalidRole(uint256 roleId) { require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role"); _; } /** * @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`. * `initialMembers` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createSharedRole( uint256 roleId, uint256 managingRoleId, address[] memory initialMembers ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Shared; role.managingRole = managingRoleId; role.sharedRoleMembership.init(initialMembers); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage a shared role" ); } /** * @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`. * `initialMember` will be immediately added to the role. * @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already * initialized. */ function _createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) internal onlyInvalidRole(roleId) { Role storage role = roles[roleId]; role.roleType = RoleType.Exclusive; role.managingRole = managingRoleId; role.exclusiveRoleMembership.init(initialMember); require( roles[managingRoleId].roleType != RoleType.Invalid, "Attempted to use an invalid role to manage an exclusive role" ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /** * @title Interface for a registry of contracts and contract creators. */ interface RegistryInterface { /** * @notice Registers a new contract. * @dev Only authorized contract creators can call this method. * @param parties an array of addresses who become parties in the contract. * @param contractAddress defines the address of the deployed contract. */ function registerContract(address[] calldata parties, address contractAddress) external; /** * @notice Returns whether the contract has been registered with the registry. * @dev If it is registered, it is an authorized participant in the UMA system. * @param contractAddress address of the contract. * @return bool indicates whether the contract is registered. */ function isContractRegistered(address contractAddress) external view returns (bool); /** * @notice Returns a list of all contracts that are associated with a particular party. * @param party address of the party. * @return an array of the contracts the party is registered to. */ function getRegisteredContracts(address party) external view returns (address[] memory); /** * @notice Returns all registered contracts. * @return all registered contract addresses within the system. */ function getAllRegisteredContracts() external view returns (address[] memory); /** * @notice Adds a party to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be added to the contract. */ function addPartyToContract(address party) external; /** * @notice Removes a party member to the calling contract. * @dev msg.sender must be the contract to which the party member is added. * @param party address to be removed from the contract. */ function removePartyFromContract(address party) external; /** * @notice checks if an address is a party in a contract. * @param party party to check. * @param contractAddress address to check against the party. * @return bool indicating if the address is a party of the contract. */ function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./MultiRole.sol"; import "../interfaces/ExpandedIERC20.sol"; /** * @title An ERC20 with permissioned burning and minting. The contract deployer will initially * be the owner who is capable of adding new roles. */ contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole { enum Roles { // Can set the minter and burner. Owner, // Addresses that can mint new tokens. Minter, // Addresses that can burn tokens that address owns. Burner } /** * @notice Constructs the ExpandedERC20. * @param _tokenName The name which describes the new token. * @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _tokenDecimals The number of decimals to define token precision. */ constructor( string memory _tokenName, string memory _tokenSymbol, uint8 _tokenDecimals ) public ERC20(_tokenName, _tokenSymbol) { _setupDecimals(_tokenDecimals); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0)); _createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0)); } /** * @dev Mints `value` tokens to `recipient`, returning true on success. * @param recipient address to mint to. * @param value amount of tokens to mint. * @return True if the mint succeeded, or False. */ function mint(address recipient, uint256 value) external override onlyRoleHolder(uint256(Roles.Minter)) returns (bool) { _mint(recipient, value); return true; } /** * @dev Burns `value` tokens owned by `msg.sender`. * @param value amount of tokens to burn. */ function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) { _burn(msg.sender, value); } /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external virtual override { addMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external virtual override { addMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external virtual override { resetMember(uint256(Roles.Owner), account); } } pragma solidity ^0.6.0; import "../../math/SafeMath.sol"; import "../../utils/Arrays.sol"; import "../../utils/Counters.sol"; import "./ERC20.sol"; /** * @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and * total supply at the time are recorded for later access. * * This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. * In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different * accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be * used to create an efficient ERC20 forking mechanism. * * Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a * snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot * id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id * and the account address. * * ==== Gas Costs * * Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log * n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much * smaller since identical balances in subsequent snapshots are stored as a single entry. * * There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is * only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent * transfers will have normal cost until the next snapshot, and so on. */ abstract contract ERC20Snapshot is ERC20 { // Inspired by Jordi Baylina's MiniMeToken to record historical balances: // https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol using SafeMath for uint256; using Arrays for uint256[]; using Counters for Counters.Counter; // Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a // Snapshot struct, but that would impede usage of functions that work on an array. struct Snapshots { uint256[] ids; uint256[] values; } mapping (address => Snapshots) private _accountBalanceSnapshots; Snapshots private _totalSupplySnapshots; // Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid. Counters.Counter private _currentSnapshotId; /** * @dev Emitted by {_snapshot} when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * * Emits a {Snapshot} event that contains the same id. * * {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a * set of accounts, for example using {AccessControl}, or it may be open to the public. * * [WARNING] * ==== * While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking, * you must consider that it can potentially be used by attackers in two ways. * * First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow * logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target * specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs * section above. * * We haven't measured the actual numbers; if this is something you're interested in please reach out to us. * ==== */ function _snapshot() internal virtual returns (uint256) { _currentSnapshotId.increment(); uint256 currentId = _currentSnapshotId.current(); emit Snapshot(currentId); return currentId; } /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]); return snapshotted ? value : balanceOf(account); } /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) public view returns(uint256) { (bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots); return snapshotted ? value : totalSupply(); } // _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the // snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value. // The same is true for the total supply and _mint and _burn. function _transfer(address from, address to, uint256 value) internal virtual override { _updateAccountSnapshot(from); _updateAccountSnapshot(to); super._transfer(from, to, value); } function _mint(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._mint(account, value); } function _burn(address account, uint256 value) internal virtual override { _updateAccountSnapshot(account); _updateTotalSupplySnapshot(); super._burn(account, value); } function _valueAt(uint256 snapshotId, Snapshots storage snapshots) private view returns (bool, uint256) { require(snapshotId > 0, "ERC20Snapshot: id is 0"); // solhint-disable-next-line max-line-length require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id"); // When a valid snapshot is queried, there are three possibilities: // a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never // created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds // to this id is the current one. // b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the // requested id, and its value is the one to return. // c) More snapshots were created after the requested one, and the queried value was later modified. There will be // no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is // larger than the requested one. // // In summary, we need to find an element in an array, returning the index of the smallest value that is larger if // it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does // exactly this. uint256 index = snapshots.ids.findUpperBound(snapshotId); if (index == snapshots.ids.length) { return (false, 0); } else { return (true, snapshots.values[index]); } } function _updateAccountSnapshot(address account) private { _updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account)); } function _updateTotalSupplySnapshot() private { _updateSnapshot(_totalSupplySnapshots, totalSupply()); } function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private { uint256 currentId = _currentSnapshotId.current(); if (_lastSnapshotId(snapshots.ids) < currentId) { snapshots.ids.push(currentId); snapshots.values.push(currentValue); } } function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) { if (ids.length == 0) { return 0; } else { return ids[ids.length - 1]; } } } pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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 {ERC20MinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; 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; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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); } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../math/Math.sol"; /** * @dev Collection of functions related to array types. */ library Arrays { /** * @dev Searches a sorted `array` and returns the first index that contains * a value greater or equal to `element`. If no such index exists (i.e. all * values in the array are strictly less than `element`), the array length is * returned. Time complexity O(log n). * * `array` is expected to be sorted in ascending order, and to contain no * repeated elements. */ function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) { if (array.length == 0) { return 0; } uint256 low = 0; uint256 high = array.length; while (low < high) { uint256 mid = Math.average(low, high); // Note that mid will always be strictly less than high (i.e. it will be a valid array index) // because Math.average rounds down (it does integer division with truncation). if (array[mid] > element) { high = mid; } else { low = mid + 1; } } // At this point `low` is the exclusive upper bound. We will return the inclusive upper bound. if (low > 0 && array[low - 1] == element) { return low - 1; } else { return low; } } } pragma solidity ^0.6.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); } } pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the * upgrade process for Voting.sol. * @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only * the ones that need to be performed atomically. */ contract VotingUpgrader { // Existing governor is the only one who can initiate the upgrade. address public governor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public newVoting; // Address to call setMigrated on the old voting contract. address public setMigratedAddress; /** * @notice Removes an address from the whitelist. * @param _governor the Governor contract address. * @param _existingVoting the current/existing Voting contract address. * @param _newVoting the new Voting deployment address. * @param _finder the Finder contract address. * @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to * old voting contract (used to claim rewards on others' behalf). Note: this address * can always be changed by the voters. */ constructor( address _governor, address _existingVoting, address _newVoting, address _finder, address _setMigratedAddress ) public { governor = _governor; existingVoting = Voting(_existingVoting); newVoting = _newVoting; finder = Finder(_finder); setMigratedAddress = _setMigratedAddress; } /** * @notice Performs the atomic portion of the upgrade process. * @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and * returns ownership of the existing Voting contract and Finder back to the Governor. */ function upgrade() external { require(msg.sender == governor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting); // Set the preset "migrated" address to allow this address to claim rewards on voters' behalf. // This also effectively shuts down the existing voting contract so new votes cannot be triggered. existingVoting.setMigrated(setMigratedAddress); // Transfer back ownership of old voting contract and the finder to the governor. existingVoting.transferOwnership(governor); finder.transferOwnership(governor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/FinderInterface.sol"; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces. */ contract Finder is FinderInterface, Ownable { mapping(bytes32 => address) public interfacesImplemented; event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress); /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 of the interface name that is either changed or registered. * @param implementationAddress address of the implementation contract. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external override onlyOwner { interfacesImplemented[interfaceName] = implementationAddress; emit InterfaceImplementationChanged(interfaceName, implementationAddress); } /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the defined interface. */ function getImplementationAddress(bytes32 interfaceName) external view override returns (address) { address implementationAddress = interfacesImplemented[interfaceName]; require(implementationAddress != address(0x0), "Implementation not found"); return implementationAddress; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../oracle/implementation/Finder.sol"; import "../oracle/implementation/Constants.sol"; import "../oracle/implementation/Voting.sol"; /** * @title A contract to track a whitelist of addresses. */ contract Umip3Upgrader { // Existing governor is the only one who can initiate the upgrade. address public existingGovernor; // Existing Voting contract needs to be informed of the address of the new Voting contract. Voting public existingVoting; // New governor will be the new owner of the finder. address public newGovernor; // Finder contract to push upgrades to. Finder public finder; // Addresses to upgrade. address public voting; address public identifierWhitelist; address public store; address public financialContractsAdmin; address public registry; constructor( address _existingGovernor, address _existingVoting, address _finder, address _voting, address _identifierWhitelist, address _store, address _financialContractsAdmin, address _registry, address _newGovernor ) public { existingGovernor = _existingGovernor; existingVoting = Voting(_existingVoting); finder = Finder(_finder); voting = _voting; identifierWhitelist = _identifierWhitelist; store = _store; financialContractsAdmin = _financialContractsAdmin; registry = _registry; newGovernor = _newGovernor; } function upgrade() external { require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor."); // Change the addresses in the Finder. finder.changeImplementationAddress(OracleInterfaces.Oracle, voting); finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist); finder.changeImplementationAddress(OracleInterfaces.Store, store); finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin); finder.changeImplementationAddress(OracleInterfaces.Registry, registry); // Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated. finder.transferOwnership(newGovernor); // Inform the existing Voting contract of the address of the new Voting contract and transfer its // ownership to the new governor to allow for any future changes to the migrated contract. existingVoting.setMigrated(voting); existingVoting.transferOwnership(newGovernor); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracleAncillary is OracleAncillaryInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; bytes ancillaryData; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices; QueryPoint[] private requestedPrices; event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData); event PushedPrice( address indexed pusher, bytes32 indexed identifier, uint256 time, bytes ancillaryData, int256 price ); constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) { // New query, enqueue it for review. queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time, ancillaryData)); emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData, int256 price ) external { verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time][ancillaryData]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } emit PushedPrice(msg.sender, identifier, time, ancillaryData, price); } // Checks whether a price has been resolved. function hasPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice( bytes32 identifier, uint256 time, bytes memory ancillaryData ) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time][ancillaryData]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../implementation/Constants.sol"; // A mock oracle used for testing. contract MockOracle is OracleInterface, Testable { // Represents an available price. Have to keep a separate bool to allow for price=0. struct Price { bool isAvailable; int256 price; // Time the verified price became available. uint256 verifiedTime; } // The two structs below are used in an array and mapping to keep track of prices that have been requested but are // not yet available. struct QueryIndex { bool isValid; uint256 index; } // Represents a (identifier, time) point that has been queried. struct QueryPoint { bytes32 identifier; uint256 time; } // Reference to the Finder. FinderInterface private finder; // Conceptually we want a (time, identifier) -> price map. mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices; // The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements. // Can we generalize this data structure? mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices; QueryPoint[] private requestedPrices; constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); } // Enqueues a request (if a request isn't already present) for the given (identifier, time) pair. function requestPrice(bytes32 identifier, uint256 time) public override { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) { // New query, enqueue it for review. queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length); requestedPrices.push(QueryPoint(identifier, time)); } } // Pushes the verified price for a requested query. function pushPrice( bytes32 identifier, uint256 time, int256 price ) external { verifiedPrices[identifier][time] = Price(true, price, getCurrentTime()); QueryIndex storage queryIndex = queryIndices[identifier][time]; require(queryIndex.isValid, "Can't push prices that haven't been requested"); // Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with // the contents of the last index (unless it is the last index). uint256 indexToReplace = queryIndex.index; delete queryIndices[identifier][time]; uint256 lastIndex = requestedPrices.length - 1; if (lastIndex != indexToReplace) { QueryPoint storage queryToCopy = requestedPrices[lastIndex]; queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace; requestedPrices[indexToReplace] = queryToCopy; } } // Checks whether a price has been resolved. function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; return lookup.isAvailable; } // Gets a price that has already been resolved. function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) { require(_getIdentifierWhitelist().isIdentifierSupported(identifier)); Price storage lookup = verifiedPrices[identifier][time]; require(lookup.isAvailable); return lookup.price; } // Gets the queries that still need verified prices. function getPendingQueries() external view returns (QueryPoint[] memory) { return requestedPrices; } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OracleInterface.sol"; import "./Constants.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title Takes proposals for certain governance actions and allows UMA token holders to vote on them. */ contract Governor is MultiRole, Testable { using SafeMath for uint256; using Address for address; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the proposer. Proposer // Address that can make proposals. } struct Transaction { address to; uint256 value; bytes data; } struct Proposal { Transaction[] transactions; uint256 requestTime; } FinderInterface private finder; Proposal[] public proposals; /**************************************** * EVENTS * ****************************************/ // Emitted when a new proposal is created. event NewProposal(uint256 indexed id, Transaction[] transactions); // Emitted when an existing proposal is executed. event ProposalExecuted(uint256 indexed id, uint256 transactionIndex); /** * @notice Construct the Governor contract. * @param _finderAddress keeps track of all contracts within the system based on their interfaceName. * @param _startingId the initial proposal id that the contract will begin incrementing from. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _finderAddress, uint256 _startingId, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender); // Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite // other storage slots in the contract. uint256 maxStartingId = 10**18; require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18"); // This just sets the initial length of the array to the startingId since modifying length directly has been // disallowed in solidity 0.6. assembly { sstore(proposals_slot, _startingId) } } /**************************************** * PROPOSAL ACTIONS * ****************************************/ /** * @notice Proposes a new governance action. Can only be called by the holder of the Proposer role. * @param transactions list of transactions that are being proposed. * @dev You can create the data portion of each transaction by doing the following: * ``` * const truffleContractInstance = await TruffleContract.deployed() * const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI() * ``` * Note: this method must be public because of a solidity limitation that * disallows structs arrays to be passed to external functions. */ function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) { uint256 id = proposals.length; uint256 time = getCurrentTime(); // Note: doing all of this array manipulation manually is necessary because directly setting an array of // structs in storage to an an array of structs in memory is currently not implemented in solidity :/. // Add a zero-initialized element to the proposals array. proposals.push(); // Initialize the new proposal. Proposal storage proposal = proposals[id]; proposal.requestTime = time; // Initialize the transaction array. for (uint256 i = 0; i < transactions.length; i++) { require(transactions[i].to != address(0), "The `to` address cannot be 0x0"); // If the transaction has any data with it the recipient must be a contract, not an EOA. if (transactions[i].data.length > 0) { require(transactions[i].to.isContract(), "EOA can't accept tx with data"); } proposal.transactions.push(transactions[i]); } bytes32 identifier = _constructIdentifier(id); // Request a vote on this proposal in the DVM. OracleInterface oracle = _getOracle(); IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist(); supportedIdentifiers.addSupportedIdentifier(identifier); oracle.requestPrice(identifier, time); supportedIdentifiers.removeSupportedIdentifier(identifier); emit NewProposal(id, transactions); } /** * @notice Executes a proposed governance action that has been approved by voters. * @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions. * @param id unique id for the executed proposal. * @param transactionIndex unique transaction index for the executed proposal. */ function executeProposal(uint256 id, uint256 transactionIndex) external payable { Proposal storage proposal = proposals[id]; int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime); Transaction memory transaction = proposal.transactions[transactionIndex]; require( transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0), "Previous tx not yet executed" ); require(transaction.to != address(0), "Tx already executed"); require(price != 0, "Proposal was rejected"); require(msg.value == transaction.value, "Must send exact amount of ETH"); // Delete the transaction before execution to avoid any potential re-entrancy issues. delete proposal.transactions[transactionIndex]; require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed"); emit ProposalExecuted(id, transactionIndex); } /**************************************** * GOVERNOR STATE GETTERS * ****************************************/ /** * @notice Gets the total number of proposals (includes executed and non-executed). * @return uint256 representing the current number of proposals. */ function numProposals() external view returns (uint256) { return proposals.length; } /** * @notice Gets the proposal data for a particular id. * @dev after a proposal is executed, its data will be zeroed out, except for the request time. * @param id uniquely identify the identity of the proposal. * @return proposal struct containing transactions[] and requestTime. */ function getProposal(uint256 id) external view returns (Proposal memory) { return proposals[id]; } /**************************************** * PRIVATE GETTERS AND FUNCTIONS * ****************************************/ function _executeCall( address to, uint256 value, bytes memory data ) private returns (bool) { // Mostly copied from: // solhint-disable-next-line max-line-length // https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31 // solhint-disable-next-line no-inline-assembly bool success; assembly { let inputData := add(data, 0x20) let inputDataSize := mload(data) success := call(gas(), to, value, inputData, inputDataSize, 0, 0) } return success; } function _getOracle() private view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Returns a UTF-8 identifier representing a particular admin proposal. // The identifier is of the form "Admin n", where n is the proposal id provided. function _constructIdentifier(uint256 id) internal pure returns (bytes32) { bytes32 bytesId = _uintToUtf8(id); return _addPrefix(bytesId, "Admin ", 6); } // This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type. // If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits. // This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801. function _uintToUtf8(uint256 v) internal pure returns (bytes32) { bytes32 ret; if (v == 0) { // Handle 0 case explicitly. ret = "0"; } else { // Constants. uint256 bitsPerByte = 8; uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10. uint256 utf8NumberOffset = 48; while (v > 0) { // Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which // translates to the beginning of the UTF-8 representation. ret = ret >> bitsPerByte; // Separate the last digit that remains in v by modding by the base of desired output representation. uint256 leastSignificantDigit = v % base; // Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character. bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset); // The top byte of ret has already been cleared to make room for the new digit. // Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched. ret |= utf8Digit << (31 * bitsPerByte); // Divide v by the base to remove the digit that was just added. v /= base; } } return ret; } // This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other. // `input` is the UTF-8 that should have the prefix prepended. // `prefix` is the UTF-8 that should be prepended onto input. // `prefixLength` is number of UTF-8 characters represented by `prefix`. // Notes: // 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented // by the bytes32 output. // 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result. function _addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) internal pure returns (bytes32) { // Downshift `input` to open space at the "front" of the bytes32 bytes32 shiftedInput = input >> (prefixLength * 8); return shiftedInput | prefix; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Governor.sol"; // GovernorTest exposes internal methods in the Governor for testing. contract GovernorTest is Governor { constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {} function addPrefix( bytes32 input, bytes32 prefix, uint256 prefixLength ) external pure returns (bytes32) { return _addPrefix(input, prefix, prefixLength); } function uintToUtf8(uint256 v) external pure returns (bytes32 ret) { return _uintToUtf8(v); } function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) { return _constructIdentifier(id); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/StoreInterface.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "../interfaces/IdentifierWhitelistInterface.sol"; import "../interfaces/OptimisticOracleInterface.sol"; import "./Constants.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/AddressWhitelist.sol"; /** * @title Optimistic Requester. * @notice Optional interface that requesters can implement to receive callbacks. * @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ interface OptimisticRequester { /** * @notice Callback for proposals. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. */ function priceProposed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external; /** * @notice Callback for disputes. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param refund refund received in the case that refundOnDispute was enabled. */ function priceDisputed( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 refund ) external; /** * @notice Callback for settlement. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data of the price being requested. * @param price price that was resolved by the escalation process. */ function priceSettled( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 price ) external; } /** * @title Optimistic Oracle. * @notice Pre-DVM escalation contract that allows faster settlement. */ contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; event RequestPrice( address indexed requester, bytes32 identifier, uint256 timestamp, bytes ancillaryData, address currency, uint256 reward, uint256 finalFee ); event ProposePrice( address indexed requester, address indexed proposer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice, uint256 expirationTimestamp, address currency ); event DisputePrice( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 proposedPrice ); event Settle( address indexed requester, address indexed proposer, address indexed disputer, bytes32 identifier, uint256 timestamp, bytes ancillaryData, int256 price, uint256 payout ); mapping(bytes32 => Request) public requests; // Finder to provide addresses for DVM contracts. FinderInterface public finder; // Default liveness value for all price requests. uint256 public defaultLiveness; /** * @notice Constructor. * @param _liveness default liveness applied to each price request. * @param _finderAddress finder to use to get addresses of DVM contracts. * @param _timerAddress address of the timer contract. Should be 0x0 in prod. */ constructor( uint256 _liveness, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { finder = FinderInterface(_finderAddress); _validateLiveness(_liveness); defaultLiveness = _liveness; } /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid"); require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier"); require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency"); require(timestamp <= getCurrentTime(), "Timestamp in future"); require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data"); uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue; requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({ proposer: address(0), disputer: address(0), currency: currency, settled: false, refundOnDispute: false, proposedPrice: 0, resolvedPrice: 0, expirationTime: 0, reward: reward, finalFee: finalFee, bond: finalFee, customLiveness: 0 }); if (reward > 0) { currency.safeTransferFrom(msg.sender, address(this), reward); } emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee); // This function returns the initial proposal bond for this request, which can be customized by calling // setBond() with the same identifier and timestamp. return finalFee.mul(2); } /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external override nonReentrant() returns (uint256 totalBond) { require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested"); Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData); request.bond = bond; // Total bond is the final fee + the newly set bond. return bond.add(request.finalFee); } /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setRefundOnDispute: Requested" ); _getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true; } /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external override nonReentrant() { require( getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setCustomLiveness: Requested" ); _validateLiveness(customLiveness); _getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness; } /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public override nonReentrant() returns (uint256 totalBond) { require(proposer != address(0), "proposer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Requested, "proposePriceFor: Requested" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.proposer = proposer; request.proposedPrice = proposedPrice; // If a custom liveness has been set, use it instead of the default. request.expirationTime = getCurrentTime().add( request.customLiveness != 0 ? request.customLiveness : defaultLiveness ); totalBond = request.bond.add(request.finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } emit ProposePrice( requester, proposer, identifier, timestamp, ancillaryData, proposedPrice, request.expirationTime, address(request.currency) ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {} } /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice); } /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public override nonReentrant() returns (uint256 totalBond) { require(disputer != address(0), "disputer address must be non 0"); require( getState(requester, identifier, timestamp, ancillaryData) == State.Proposed, "disputePriceFor: Proposed" ); Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.disputer = disputer; uint256 finalFee = request.finalFee; uint256 bond = request.bond; totalBond = bond.add(finalFee); if (totalBond > 0) { request.currency.safeTransferFrom(msg.sender, address(this), totalBond); } StoreInterface store = _getStore(); // Avoids stack too deep compilation error. { // Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it // proportionally more expensive to delay the resolution even if the proposer and disputer are the same // party. uint256 burnedBond = _computeBurnedBond(request); // The total fee is the burned bond and the final fee added together. uint256 totalFee = finalFee.add(burnedBond); if (totalFee > 0) { request.currency.safeIncreaseAllowance(address(store), totalFee); _getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee)); } } _getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)); // Compute refund. uint256 refund = 0; if (request.reward > 0 && request.refundOnDispute) { refund = request.reward; request.reward = 0; request.currency.safeTransfer(requester, refund); } emit DisputePrice( requester, request.proposer, disputer, identifier, timestamp, ancillaryData, request.proposedPrice ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {} } /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override returns (uint256 totalBond) { // Note: re-entrancy guard is done in the inner call. return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData); } /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (int256) { if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) { _settle(msg.sender, identifier, timestamp, ancillaryData); } return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice; } /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external override nonReentrant() returns (uint256 payout) { return _settle(requester, identifier, timestamp, ancillaryData); } /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (Request memory) { return _getRequest(requester, identifier, timestamp, ancillaryData); } /** * @notice Computes the current state of a price request. See the State enum for more details. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (State) { Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); if (address(request.currency) == address(0)) { return State.Invalid; } if (request.proposer == address(0)) { return State.Requested; } if (request.settled) { return State.Settled; } if (request.disputer == address(0)) { return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed; } return _getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester)) ? State.Resolved : State.Disputed; } /** * @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return boolean indicating true if price exists and false if not. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view override returns (bool) { State state = getState(requester, identifier, timestamp, ancillaryData); return state == State.Settled || state == State.Resolved || state == State.Expired; } /** * @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute. * @param ancillaryData ancillary data of the price being requested. * @param requester sender of the initial price request. * @return the stampped ancillary bytes. */ function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) { return _stampAncillaryData(ancillaryData, requester); } function _getId( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private pure returns (bytes32) { return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData)); } function _settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private returns (uint256 payout) { State state = getState(requester, identifier, timestamp, ancillaryData); // Set it to settled so this function can never be entered again. Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData); request.settled = true; if (state == State.Expired) { // In the expiry case, just pay back the proposer's bond and final fee along with the reward. request.resolvedPrice = request.proposedPrice; payout = request.bond.add(request.finalFee).add(request.reward); request.currency.safeTransfer(request.proposer, payout); } else if (state == State.Resolved) { // In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward). request.resolvedPrice = _getOracle().getPrice( identifier, timestamp, _stampAncillaryData(ancillaryData, requester) ); bool disputeSuccess = request.resolvedPrice != request.proposedPrice; uint256 bond = request.bond; // Unburned portion of the loser's bond = 1 - burned bond. uint256 unburnedBond = bond.sub(_computeBurnedBond(request)); // Winner gets: // - Their bond back. // - The unburned portion of the loser's bond. // - Their final fee back. // - The request reward (if not already refunded -- if refunded, it will be set to 0). payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward); request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout); } else { revert("_settle: not settleable"); } emit Settle( requester, request.proposer, request.disputer, identifier, timestamp, ancillaryData, request.resolvedPrice, payout ); // Callback. if (address(requester).isContract()) try OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice) {} catch {} } function _getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) private view returns (Request storage) { return requests[_getId(requester, identifier, timestamp, ancillaryData)]; } function _computeBurnedBond(Request storage request) private view returns (uint256) { // burnedBond = floor(bond / 2) return request.bond.div(2); } function _validateLiveness(uint256 _liveness) private pure { require(_liveness < 5200 weeks, "Liveness too large"); require(_liveness > 0, "Liveness cannot be 0"); } function _getOracle() internal view returns (OracleAncillaryInterface) { return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getCollateralWhitelist() internal view returns (AddressWhitelist) { return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } // Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it. function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) { return abi.encodePacked(ancillaryData, "OptimisticOracle", requester); } } pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that allows financial contracts to pay oracle fees for their use of the system. */ interface StoreInterface { /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable; /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external; /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty); /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due. */ function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length of a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered. // Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Lockable.sol"; /** * @title A contract to track a whitelist of addresses. */ contract AddressWhitelist is Ownable, Lockable { enum Status { None, In, Out } mapping(address => Status) public whitelist; address[] public whitelistIndices; event AddedToWhitelist(address indexed addedAddress); event RemovedFromWhitelist(address indexed removedAddress); /** * @notice Adds an address to the whitelist. * @param newElement the new address to add. */ function addToWhitelist(address newElement) external nonReentrant() onlyOwner { // Ignore if address is already included if (whitelist[newElement] == Status.In) { return; } // Only append new addresses to the array, never a duplicate if (whitelist[newElement] == Status.None) { whitelistIndices.push(newElement); } whitelist[newElement] = Status.In; emit AddedToWhitelist(newElement); } /** * @notice Removes an address from the whitelist. * @param elementToRemove the existing address to remove. */ function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner { if (whitelist[elementToRemove] != Status.Out) { whitelist[elementToRemove] = Status.Out; emit RemovedFromWhitelist(elementToRemove); } } /** * @notice Checks whether an address is on the whitelist. * @param elementToCheck the address to check. * @return True if `elementToCheck` is on the whitelist, or False. */ function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) { return whitelist[elementToCheck] == Status.In; } /** * @notice Gets all addresses that are currently included in the whitelist. * @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out * of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we * can modify the implementation so that when addresses are removed, the last addresses in the array is moved to * the empty index. * @return activeWhitelist the list of addresses on the whitelist. */ function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) { // Determine size of whitelist first uint256 activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { if (whitelist[whitelistIndices[i]] == Status.In) { activeCount++; } } // Populate whitelist activeWhitelist = new address[](activeCount); activeCount = 0; for (uint256 i = 0; i < whitelistIndices.length; i++) { address addr = whitelistIndices[i]; if (whitelist[addr] == Status.In) { activeWhitelist[activeCount] = addr; activeCount++; } } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../OptimisticOracle.sol"; // This is just a test contract to make requests to the optimistic oracle. contract OptimisticRequesterTest is OptimisticRequester { OptimisticOracle optimisticOracle; bool public shouldRevert = false; // State variables to track incoming calls. bytes32 public identifier; uint256 public timestamp; bytes public ancillaryData; uint256 public refund; int256 public price; // Implement collateralCurrency so that this contract simulates a financial contract whose collateral // token can be fetched by off-chain clients. IERC20 public collateralCurrency; // Manually set an expiration timestamp to simulate expiry price requests uint256 public expirationTimestamp; constructor(OptimisticOracle _optimisticOracle) public { optimisticOracle = _optimisticOracle; } function requestPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, IERC20 currency, uint256 reward ) external { // Set collateral currency to last requested currency: collateralCurrency = currency; currency.approve(address(optimisticOracle), reward); optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward); } function settleAndGetPrice( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external returns (int256) { return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData); } function setBond( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 bond ) external { optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond); } function setRefundOnDispute( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external { optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData); } function setCustomLiveness( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 customLiveness ) external { optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness); } function setRevert(bool _shouldRevert) external { shouldRevert = _shouldRevert; } function setExpirationTimestamp(uint256 _expirationTimestamp) external { expirationTimestamp = _expirationTimestamp; } function clearState() external { delete identifier; delete timestamp; delete refund; delete price; } function priceProposed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; } function priceDisputed( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, uint256 _refund ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; refund = _refund; } function priceSettled( bytes32 _identifier, uint256 _timestamp, bytes memory _ancillaryData, int256 _price ) external override { require(!shouldRevert); identifier = _identifier; timestamp = _timestamp; ancillaryData = _ancillaryData; price = _price; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/StoreInterface.sol"; /** * @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token. */ contract Store is StoreInterface, Withdrawable, Testable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeERC20 for IERC20; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, Withdrawer } FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee. FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee. mapping(address => FixedPoint.Unsigned) public finalFees; uint256 public constant SECONDS_PER_WEEK = 604800; /**************************************** * EVENTS * ****************************************/ event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee); event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc); event NewFinalFee(FixedPoint.Unsigned newFinalFee); /** * @notice Construct the Store contract. */ constructor( FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc, FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc, address _timerAddress ) public Testable(_timerAddress) { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender); _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender); setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc); setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc); } /**************************************** * ORACLE FEE CALCULATION AND PAYMENT * ****************************************/ /** * @notice Pays Oracle fees in ETH to the store. * @dev To be used by contracts whose margin currency is ETH. */ function payOracleFees() external payable override { require(msg.value > 0, "Value sent can't be zero"); } /** * @notice Pays oracle fees in the margin currency, erc20Address, to the store. * @dev To be used if the margin currency is an ERC20 token rather than ETH. * @param erc20Address address of the ERC20 token used to pay the fee. * @param amount number of tokens to transfer. An approval for at least this amount must exist. */ function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override { IERC20 erc20 = IERC20(erc20Address); require(amount.isGreaterThan(0), "Amount sent can't be zero"); erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue); } /** * @notice Computes the regular oracle fees that a contract should pay for a period. * @dev The late penalty is similar to the regular fee in that is is charged per second over the period between * startTime and endTime. * * The late penalty percentage increases over time as follows: * * - 0-1 week since startTime: no late penalty * * - 1-2 weeks since startTime: 1x late penalty percentage is applied * * - 2-3 weeks since startTime: 2x late penalty percentage is applied * * - ... * * @param startTime defines the beginning time from which the fee is paid. * @param endTime end time until which the fee is paid. * @param pfc "profit from corruption", or the maximum amount of margin currency that a * token sponsor could extract from the contract through corrupting the price feed in their favor. * @return regularFee amount owed for the duration from start to end time for the given pfc. * @return latePenalty penalty percentage, if any, for paying the fee after the deadline. */ function computeRegularFee( uint256 startTime, uint256 endTime, FixedPoint.Unsigned calldata pfc ) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) { uint256 timeDiff = endTime.sub(startTime); // Multiply by the unscaled `timeDiff` first, to get more accurate results. regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc); // Compute how long ago the start time was to compute the delay penalty. uint256 paymentDelay = getCurrentTime().sub(startTime); // Compute the additional percentage (per second) that will be charged because of the penalty. // Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to // 0, causing no penalty to be charged. FixedPoint.Unsigned memory penaltyPercentagePerSecond = weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK)); // Apply the penaltyPercentagePerSecond to the payment period. latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond); } /** * @notice Computes the final oracle fees that a contract should pay at settlement. * @param currency token used to pay the final fee. * @return finalFee amount due denominated in units of `currency`. */ function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) { return finalFees[currency]; } /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Sets a new oracle fee per second. * @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle. */ function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { // Oracle fees at or over 100% don't make sense. require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second."); fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc; emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc); } /** * @notice Sets a new weekly delay fee. * @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment. */ function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc) public onlyRoleHolder(uint256(Roles.Owner)) { require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%"); weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc; emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc); } /** * @notice Sets a new final fee for a particular currency. * @param currency defines the token currency used to pay the final fee. * @param newFinalFee final fee amount. */ function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee) public onlyRoleHolder(uint256(Roles.Owner)) { finalFees[currency] = newFinalFee; emit NewFinalFee(newFinalFee); } } /** * Withdrawable contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./MultiRole.sol"; /** * @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds. */ abstract contract Withdrawable is MultiRole { using SafeERC20 for IERC20; uint256 private roleId; /** * @notice Withdraws ETH from the contract. */ function withdraw(uint256 amount) external onlyRoleHolder(roleId) { Address.sendValue(msg.sender, amount); } /** * @notice Withdraws ERC20 tokens from the contract. * @param erc20Address ERC20 token to withdraw. * @param amount amount of tokens to withdraw. */ function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) { IERC20 erc20 = IERC20(erc20Address); erc20.safeTransfer(msg.sender, amount); } /** * @notice Internal method that allows derived contracts to create a role for withdrawal. * @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function * properly. * @param newRoleId ID corresponding to role whose members can withdraw. * @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership. * @param withdrawerAddress new manager of withdrawable role. */ function _createWithdrawRole( uint256 newRoleId, uint256 managingRoleId, address withdrawerAddress ) internal { roleId = newRoleId; _createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress); } /** * @notice Internal method that allows derived contracts to choose the role for withdrawal. * @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be * called by the derived class for this contract to function properly. * @param setRoleId ID corresponding to role whose members can withdraw. */ function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) { roleId = setRoleId; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/interfaces/StoreInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/AdministrateeInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title FeePayer contract. * @notice Provides fee payment functionality for the ExpiringMultiParty contract. * contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`. */ abstract contract FeePayer is AdministrateeInterface, Testable, Lockable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /**************************************** * FEE PAYER DATA STRUCTURES * ****************************************/ // The collateral currency used to back the positions in this contract. IERC20 public collateralCurrency; // Finder contract used to look up addresses for UMA system contracts. FinderInterface public finder; // Tracks the last block time when the fees were paid. uint256 private lastPaymentTime; // Tracks the cumulative fees that have been paid by the contract for use by derived contracts. // The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee). // Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ... // For example: // The cumulativeFeeMultiplier should start at 1. // If a 1% fee is charged, the multiplier should update to .99. // If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801). FixedPoint.Unsigned public cumulativeFeeMultiplier; /**************************************** * EVENTS * ****************************************/ event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee); event FinalFeesPaid(uint256 indexed amount); /**************************************** * MODIFIERS * ****************************************/ // modifier that calls payRegularFees(). modifier fees virtual { // Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the // regular fee applied linearly since the last update. This implies that the compounding rate depends on the // frequency of update transactions that have this modifier, and it never reaches the ideal of continuous // compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the // complexity of compounding data on-chain. payRegularFees(); _; } /** * @notice Constructs the FeePayer contract. Called by child contracts. * @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, address _timerAddress ) public Testable(_timerAddress) { collateralCurrency = IERC20(_collateralAddress); finder = FinderInterface(_finderAddress); lastPaymentTime = getCurrentTime(); cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1); } /**************************************** * FEE PAYMENT FUNCTIONS * ****************************************/ /** * @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract. * @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee * in a week or more then a late penalty is applied which is sent to the caller. If the amount of * fees owed are greater than the pfc, then this will pay as much as possible from the available collateral. * An event is only fired if the fees charged are greater than 0. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). * This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. */ function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) { uint256 time = getCurrentTime(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract. ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) = getOutstandingRegularFees(time); lastPaymentTime = time; // If there are no fees to pay then exit early. if (totalPaid.isEqual(0)) { return totalPaid; } emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue); _adjustCumulativeFeeMultiplier(totalPaid, collateralPool); if (regularFee.isGreaterThan(0)) { StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue); store.payOracleFeesErc20(address(collateralCurrency), regularFee); } if (latePenalty.isGreaterThan(0)) { collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue); } return totalPaid; } /** * @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more * than the total collateral within the contract then the totalPaid returned is full contract collateral amount. * @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0. * @return regularFee outstanding unpaid regular fee. * @return latePenalty outstanding unpaid late fee for being late in previous fee payments. * @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller). */ function getOutstandingRegularFees(uint256 time) public view returns ( FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty, FixedPoint.Unsigned memory totalPaid ) { StoreInterface store = _getStore(); FixedPoint.Unsigned memory collateralPool = _pfc(); // Exit early if there is no collateral or if fees were already paid during this block. if (collateralPool.isEqual(0) || lastPaymentTime == time) { return (regularFee, latePenalty, totalPaid); } (regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool); totalPaid = regularFee.add(latePenalty); if (totalPaid.isEqual(0)) { return (regularFee, latePenalty, totalPaid); } // If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay // as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the // regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining. if (totalPaid.isGreaterThan(collateralPool)) { FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool); FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit); latePenalty = latePenalty.sub(latePenaltyReduction); deficit = deficit.sub(latePenaltyReduction); regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit)); totalPaid = collateralPool; } } /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) { return _pfc(); } /** * @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors. * @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively * pays all sponsors a pro-rata portion of the excess collateral. * @dev This will revert if PfC is 0 and this contract's collateral balance > 0. */ function gulp() external nonReentrant() { _gulp(); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee // charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not // the contract, pulls in `amount` of collateral currency. function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal { if (amount.isEqual(0)) { return; } if (payer != address(this)) { // If the payer is not the contract pull the collateral from the payer. collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue); } else { // If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate. FixedPoint.Unsigned memory collateralPool = _pfc(); // The final fee must be < available collateral or the fee will be larger than 100%. // Note: revert reason removed to save bytecode. require(collateralPool.isGreaterThan(amount)); _adjustCumulativeFeeMultiplier(amount, collateralPool); } emit FinalFeesPaid(amount.rawValue); StoreInterface store = _getStore(); collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue); store.payOracleFeesErc20(address(collateralCurrency), amount); } function _gulp() internal { FixedPoint.Unsigned memory currentPfc = _pfc(); FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); if (currentPfc.isLessThan(currentBalance)) { cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc)); } } function _pfc() internal view virtual returns (FixedPoint.Unsigned memory); function _getStore() internal view returns (StoreInterface) { return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store)); } function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) { StoreInterface store = _getStore(); return store.computeFinalFee(address(collateralCurrency)); } // Returns the user's collateral minus any fees that have been subtracted since it was originally // deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw // value should be larger than the returned value. function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory collateral) { return rawCollateral.mul(cumulativeFeeMultiplier); } // Returns the user's collateral minus any pending fees that have yet to be subtracted. function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral) internal view returns (FixedPoint.Unsigned memory) { (, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) = getOutstandingRegularFees(getCurrentTime()); if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral; // Calculate the total outstanding regular fee as a fraction of the total contract PFC. FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc()); // Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee. return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee)); } // Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees // have been taken from this contract in the past, then the raw value will be larger than the user-readable value. function _convertToRawCollateral(FixedPoint.Unsigned memory collateral) internal view returns (FixedPoint.Unsigned memory rawCollateral) { return collateral.div(cumulativeFeeMultiplier); } // Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an // actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is // decreased by so that the caller can minimize error between collateral removed and rawCollateral debited. function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove) internal returns (FixedPoint.Unsigned memory removedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove); rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue; removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral)); } // Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd // by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore // rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an // actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is // increased by so that the caller can minimize error between collateral added and rawCollateral credited. // NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it // because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral. function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd) internal returns (FixedPoint.Unsigned memory addedCollateral) { FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral); FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd); rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue; addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance); } // Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral. function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc) internal { FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc); cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Interface that all financial contracts expose to the admin. */ interface AdministrateeInterface { /** * @notice Initiates the shutdown process, in case of an emergency. */ function emergencyShutdown() external; /** * @notice A core contract method called independently or as a part of other financial contract transactions. * @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract. */ function remargin() external; /** * @notice Gets the current profit from corruption for this contract in terms of the collateral currency. * @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are * expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC. * @return pfc value for equal to the current profit from corruption denominated in collateral currency. */ function pfc() external view returns (FixedPoint.Unsigned memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FeePayer.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PricelessPositionManager is FeePayer { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; using Address for address; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement. enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } ContractState public contractState; // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; // Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`. uint256 transferPositionRequestPassTimestamp; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs. uint256 public expirationTimestamp; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // The expiry price pulled from the DVM. FixedPoint.Unsigned public expiryPrice; // Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend // the functionality of the EMP to support a wider range of financial products. FinancialProductLibrary public financialProductLibrary; /**************************************** * EVENTS * ****************************************/ event RequestTransferPosition(address indexed oldSponsor); event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor); event RequestTransferPositionCanceled(address indexed oldSponsor); event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event ContractExpired(address indexed caller); event SettleExpiredPosition( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp); /**************************************** * MODIFIERS * ****************************************/ modifier onlyPreExpiration() { _onlyPreExpiration(); _; } modifier onlyPostExpiration() { _onlyPostExpiration(); _; } modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } // Check that the current state of the pricelessPositionManager is Open. // This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration. modifier onlyOpenState() { _onlyOpenState(); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PricelessPositionManager * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _expirationTimestamp unix timestamp of when the contract will expire. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. * @param _financialProductLibraryAddress Contract providing contract state transformations. */ constructor( uint256 _expirationTimestamp, uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _timerAddress, address _financialProductLibraryAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_expirationTimestamp > getCurrentTime()); require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); expirationTimestamp = _expirationTimestamp; withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; // Initialize the financialProductLibrary at the provided address. financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Requests to transfer ownership of the caller's current position to a new sponsor address. * Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor. * @dev The liveness length is the same as the withdrawal liveness. */ function requestTransferPosition() public onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp == 0); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.transferPositionRequestPassTimestamp = requestPassTime; emit RequestTransferPosition(msg.sender); } /** * @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting * `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`. * @dev Transferring positions can only occur if the recipient does not already have a position. * @param newSponsorAddress is the address to which the position will be transferred. */ function transferPositionPassedRequest(address newSponsorAddress) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { require( _getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual( FixedPoint.fromUnscaledUint(0) ) ); PositionData storage positionData = _getPositionData(msg.sender); require( positionData.transferPositionRequestPassTimestamp != 0 && positionData.transferPositionRequestPassTimestamp <= getCurrentTime() ); // Reset transfer request. positionData.transferPositionRequestPassTimestamp = 0; positions[newSponsorAddress] = positionData; delete positions[msg.sender]; emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress); emit NewSponsor(newSponsorAddress); emit EndedSponsorPosition(msg.sender); } /** * @notice Cancels a pending transfer position request. */ function cancelTransferPosition() external onlyPreExpiration() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.transferPositionRequestPassTimestamp != 0); emit RequestTransferPositionCanceled(msg.sender); // Reset withdrawal request. positionData.transferPositionRequestPassTimestamp = 0; } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public onlyPreExpiration() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Make sure the proposed expiration of this request is not post-expiry. uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness); require(requestPassTime < expirationTimestamp); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = requestPassTime; positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external onlyPreExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public onlyPreExpiration() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(!numTokens.isGreaterThan(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the * prevailing price defined by the DVM from the `expire` function. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleExpired() external onlyPostExpiration() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired position"); // Get the current settlement price and store it. If it is not resolved will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); contractState = ContractState.ExpiredPriceReceived; } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying. FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Locks contract state in expired and requests oracle price. * @dev this function can only be called once the contract is expired and can't be re-called. */ function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() { contractState = ContractState.ExpiredPriceRequested; // Final fees do not need to be paid when sending a request to the optimistic oracle. _requestOraclePriceExpiration(expirationTimestamp); emit ContractExpired(msg.sender); } /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested` * which prevents re-entry into this function or the `expire` function. No fees are paid when calling * `emergencyShutdown` as the governor who would call the function would also receive the fees. */ function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() { require(msg.sender == _getFinancialContractsAdminAddress()); contractState = ContractState.ExpiredPriceRequested; // Expiratory time now becomes the current time (emergency shutdown time). // Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp. uint256 oldExpirationTimestamp = expirationTimestamp; expirationTimestamp = getCurrentTime(); _requestOraclePriceExpiration(expirationTimestamp); emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override onlyPreExpiration() nonReentrant() { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PricelessPositionManager. * @return totalCollateral amount of all collateral within the Expiring Multi Party Contract. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } /** * @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract * deployment. If no library was provided then no modification to the price is done. * @param price input price to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformPrice(price, requestTime); } /** * @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified * at contract deployment. If no library was provided then no modification to the identifier is done. * @param requestTime timestamp the identifier is to be used at. * @return transformedPrice price with the transformation function applied to it. * @dev This method should never revert. */ function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) { return _transformPriceIdentifier(requestTime); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position"); positionData.tokensOutstanding = newTokenCount; // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral; rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceExpiration(uint256 requestedTime) internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Increase token allowance to enable the optimistic oracle reward transfer. FixedPoint.Unsigned memory reward = _computeFinalFees(); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue); optimisticOracle.requestPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData(), collateralCurrency, reward.rawValue // Reward is equal to the final fee ); // Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee. _adjustCumulativeFeeMultiplier(reward, _pfc()); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.hasPrice( address(this), _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ) ); int256 optimisticOraclePrice = optimisticOracle.settleAndGetPrice( _transformPriceIdentifier(requestedTime), requestedTime, _getAncillaryData() ); // For now we don't want to deal with negative prices in positions. if (optimisticOraclePrice < 0) { optimisticOraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime); } // Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePriceLiquidation(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OracleInterface oracle = _getOracle(); require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyOpenState() internal view { require(contractState == ContractState.Open, "Contract state is not OPEN"); } function _onlyPreExpiration() internal view { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); } function _onlyPostExpiration() internal view { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); } function _onlyCollateralizedPosition(address sponsor) internal view { require( _getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0), "Position has no collateral" ); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal"); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { if (!numTokens.isGreaterThan(0)) { return FixedPoint.fromUnscaledUint(0); } else { return collateral.div(numTokens); } } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) { if (!address(financialProductLibrary).isContract()) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(address(tokenCurrency)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes the decimals read only method. */ interface IERC20Standard is IERC20 { /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` * (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value * {ERC20} uses, unless {_setupDecimals} is called. * * NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic * of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../../common/implementation/FixedPoint.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } /** * @title Financial product library contract * @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom * Financial product library implementations. */ abstract contract FinancialProductLibrary { using FixedPoint for FixedPoint.Unsigned; /** * @notice Transforms a given oracle price using the financial product libraries transformation logic. * @param oraclePrice input price returned by the DVM to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedOraclePrice input oraclePrice with the transformation function applied. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view virtual returns (FixedPoint.Unsigned memory) { return oraclePrice; } /** * @notice Transforms a given collateral requirement using the financial product libraries transformation logic. * @param oraclePrice input price returned by DVM used to transform the collateral requirement. * @param collateralRequirement input collateral requirement to be transformed. * @return transformedCollateralRequirement input collateral requirement with the transformation function applied. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view virtual returns (FixedPoint.Unsigned memory) { return collateralRequirement; } /** * @notice Transforms a given price identifier using the financial product libraries transformation logic. * @param priceIdentifier input price identifier defined for the financial contract. * @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier. * @return transformedPriceIdentifier input price identifier with the transformation function applied. */ function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view virtual returns (bytes32) { return priceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; // Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations. contract FinancialProductLibraryTest is FinancialProductLibrary { FixedPoint.Unsigned public priceTransformationScalar; FixedPoint.Unsigned public collateralRequirementTransformationScalar; bytes32 public transformedPriceIdentifier; bool public shouldRevert; constructor( FixedPoint.Unsigned memory _priceTransformationScalar, FixedPoint.Unsigned memory _collateralRequirementTransformationScalar, bytes32 _transformedPriceIdentifier ) public { priceTransformationScalar = _priceTransformationScalar; collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar; transformedPriceIdentifier = _transformedPriceIdentifier; } // Set the mocked methods to revert to test failed library computation. function setShouldRevert(bool _shouldRevert) public { shouldRevert = _shouldRevert; } // Create a simple price transformation function that scales the input price by the scalar for testing. function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return oraclePrice.mul(priceTransformationScalar); } // Create a simple collateral requirement transformation that doubles the input collateralRequirement. function transformCollateralRequirement( FixedPoint.Unsigned memory price, FixedPoint.Unsigned memory collateralRequirement ) public view override returns (FixedPoint.Unsigned memory) { require(!shouldRevert, "set to always reverts"); return collateralRequirement.mul(collateralRequirementTransformationScalar); } // Create a simple transformPriceIdentifier function that returns the transformed price identifier. function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime) public view override returns (bytes32) { require(!shouldRevert, "set to always reverts"); return transformedPriceIdentifier; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Testable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../common/financial-product-libraries/FinancialProductLibrary.sol"; contract ExpiringMultiPartyMock is Testable { using FixedPoint for FixedPoint.Unsigned; FinancialProductLibrary public financialProductLibrary; uint256 public expirationTimestamp; FixedPoint.Unsigned public collateralRequirement; bytes32 public priceIdentifier; constructor( address _financialProductLibraryAddress, uint256 _expirationTimestamp, FixedPoint.Unsigned memory _collateralRequirement, bytes32 _priceIdentifier, address _timerAddress ) public Testable(_timerAddress) { expirationTimestamp = _expirationTimestamp; collateralRequirement = _collateralRequirement; financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress); priceIdentifier = _priceIdentifier; } function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return price; try financialProductLibrary.transformPrice(price, requestTime) returns ( FixedPoint.Unsigned memory transformedPrice ) { return transformedPrice; } catch { return price; } } function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view returns (FixedPoint.Unsigned memory) { if (address(financialProductLibrary) == address(0)) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) { if (address(financialProductLibrary) == address(0)) return priceIdentifier; try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns ( bytes32 transformedIdentifier ) { return transformedIdentifier; } catch { return priceIdentifier; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../interfaces/OracleAncillaryInterface.sol"; import "../interfaces/VotingAncillaryInterface.sol"; // A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data. abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable { using FixedPoint for FixedPoint.Unsigned; // Events, data structures and functions not exported in the base interfaces, used for testing. event VoteCommitted( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData ); event EncryptedVote( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, bytes encryptedVote ); event VoteRevealed( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData, uint256 numTokens ); event RewardsRetrieved( address indexed voter, uint256 indexed roundId, bytes32 indexed identifier, uint256 time, bytes ancillaryData, uint256 numTokens ); event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time); event PriceResolved( uint256 indexed roundId, bytes32 indexed identifier, uint256 time, int256 price, bytes ancillaryData ); struct Round { uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken. FixedPoint.Unsigned inflationRate; // Inflation rate set for this round. FixedPoint.Unsigned gatPercentage; // Gat rate set for this round. uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until. } // Represents the status a price request has. enum RequestStatus { NotRequested, // Was never requested. Active, // Is being voted on in the current round. Resolved, // Was resolved in a previous round. Future // Is scheduled to be voted on in a future round. } // Only used as a return value in view methods -- never stored in the contract. struct RequestState { RequestStatus status; uint256 lastVotingRound; } function rounds(uint256 roundId) public view virtual returns (Round memory); function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests) public view virtual returns (RequestState[] memory); function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/MultiRole.sol"; import "../../common/implementation/Withdrawable.sol"; import "../interfaces/VotingAncillaryInterface.sol"; import "../interfaces/FinderInterface.sol"; import "./Constants.sol"; /** * @title Proxy to allow voting from another address. * @dev Allows a UMA token holder to designate another address to vote on their behalf. * Each voter must deploy their own instance of this contract. */ contract DesignatedVoting is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Owner, // Can set the Voter role. Is also permanently permissioned as the minter role. Voter // Can vote through this contract. } // Reference to the UMA Finder contract, allowing Voting upgrades to be performed // without requiring any calls to this contract. FinderInterface private finder; /** * @notice Construct the DesignatedVoting contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. * @param ownerAddress address of the owner of the DesignatedVoting contract. * @param voterAddress address to which the owner has delegated their voting power. */ constructor( address finderAddress, address ownerAddress, address voterAddress ) public { _createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress); _createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress); _setWithdrawRole(uint256(Roles.Owner)); finder = FinderInterface(finderAddress); } /**************************************** * VOTING AND REWARD FUNCTIONALITY * ****************************************/ /** * @notice Forwards a commit to Voting. * @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param hash the keccak256 hash of the price you want to vote for and a random integer salt value. */ function commitVote( bytes32 identifier, uint256 time, bytes memory ancillaryData, bytes32 hash ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().commitVote(identifier, time, ancillaryData, hash); } /** * @notice Forwards a batch commit to Voting. * @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`. */ function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchCommit(commits); } /** * @notice Forwards a reveal to Voting. * @param identifier voted on in the commit phase. EG BTC/USD price pair. * @param time specifies the unix timestamp of the price being voted on. * @param price used along with the `salt` to produce the `hash` during the commit phase. * @param salt used along with the `price` to produce the `hash` during the commit phase. */ function revealVote( bytes32 identifier, uint256 time, int256 price, bytes memory ancillaryData, int256 salt ) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt); } /** * @notice Forwards a batch reveal to Voting. * @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt. */ function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals) external onlyRoleHolder(uint256(Roles.Voter)) { _getVotingAddress().batchReveal(reveals); } /** * @notice Forwards a reward retrieval to Voting. * @dev Rewards are added to the tokens already held by this contract. * @param roundId defines the round from which voting rewards will be retrieved from. * @param toRetrieve an array of PendingRequests which rewards are retrieved from. * @return amount of rewards that the user should receive. */ function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve) public onlyRoleHolder(uint256(Roles.Voter)) returns (FixedPoint.Unsigned memory) { return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve); } function _getVotingAddress() private view returns (VotingAncillaryInterface) { return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/Withdrawable.sol"; import "./DesignatedVoting.sol"; /** * @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances. * @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract. */ contract DesignatedVotingFactory is Withdrawable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ enum Roles { Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract. } address private finder; mapping(address => DesignatedVoting) public designatedVotingContracts; /** * @notice Construct the DesignatedVotingFactory contract. * @param finderAddress keeps track of all contracts within the system based on their interfaceName. */ constructor(address finderAddress) public { finder = finderAddress; _createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender); } /** * @notice Deploys a new `DesignatedVoting` contract. * @param ownerAddress defines who will own the deployed instance of the designatedVoting contract. * @return designatedVoting a new DesignatedVoting contract. */ function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) { DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender); designatedVotingContracts[msg.sender] = designatedVoting; return designatedVoting; } /** * @notice Associates a `DesignatedVoting` instance with `msg.sender`. * @param designatedVotingAddress address to designate voting to. * @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter` * address and wants that reflected here. */ function setDesignatedVoting(address designatedVotingAddress) external { designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Withdrawable.sol"; // WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes. contract WithdrawableTest is Withdrawable { enum Roles { Governance, Withdraw } // solhint-disable-next-line no-empty-blocks constructor() public { _createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender); _createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender); } function pay() external payable { require(msg.value > 0); } function setInternalWithdrawRole(uint256 setRoleId) public { _setWithdrawRole(setRoleId); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI) * @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note: * this token should never be used to store real value since it allows permissionless minting. */ contract TestnetERC20 is ERC20 { /** * @notice Constructs the TestnetERC20. * @param _name The name which describes the new token. * @param _symbol The ticker abbreviation of the name. Ideally < 5 chars. * @param _decimals The number of decimals to define token precision. */ constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } // Sample token information. /** * @notice Mints value tokens to the owner address. * @param ownerAddress the address to mint to. * @param value the amount of tokens to mint. */ function allocateTo(address ownerAddress, uint256 value) external { _mint(ownerAddress, value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/IdentifierWhitelistInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Stores a whitelist of supported identifiers that the oracle can provide prices for. */ contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable { /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ mapping(bytes32 => bool) private supportedIdentifiers; /**************************************** * EVENTS * ****************************************/ event SupportedIdentifierAdded(bytes32 indexed identifier); event SupportedIdentifierRemoved(bytes32 indexed identifier); /**************************************** * ADMIN STATE MODIFYING FUNCTIONS * ****************************************/ /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (!supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = true; emit SupportedIdentifierAdded(identifier); } } /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner { if (supportedIdentifiers[identifier]) { supportedIdentifiers[identifier] = false; emit SupportedIdentifierRemoved(identifier); } } /**************************************** * WHITELIST GETTERS FUNCTIONS * ****************************************/ /** * @notice Checks whether an identifier is on the whitelist. * @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view override returns (bool) { return supportedIdentifiers[identifier]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/AdministrateeInterface.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Admin for financial contracts in the UMA system. * @dev Allows appropriately permissioned admin roles to interact with financial contracts. */ contract FinancialContractsAdmin is Ownable { /** * @notice Calls emergency shutdown on the provided financial contract. * @param financialContract address of the FinancialContract to be shut down. */ function callEmergencyShutdown(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.emergencyShutdown(); } /** * @notice Calls remargin on the provided financial contract. * @param financialContract address of the FinancialContract to be remargined. */ function callRemargin(address financialContract) external onlyOwner { AdministrateeInterface administratee = AdministrateeInterface(financialContract); administratee.remargin(); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../interfaces/AdministrateeInterface.sol"; // A mock implementation of AdministrateeInterface, taking the place of a financial contract. contract MockAdministratee is AdministrateeInterface { uint256 public timesRemargined; uint256 public timesEmergencyShutdown; function remargin() external override { timesRemargined++; } function emergencyShutdown() external override { timesEmergencyShutdown++; } function pfc() external view override returns (FixedPoint.Unsigned memory) { return FixedPoint.fromUnscaledUint(0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * Inspired by: * - https://github.com/pie-dao/vested-token-migration-app * - https://github.com/Uniswap/merkle-distributor * - https://github.com/balancer-labs/erc20-redeemable * * @title MerkleDistributor contract. * @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify * multiple Merkle roots distributions with customized reward currencies. * @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly. */ contract MerkleDistributor is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // A Window maps a Merkle root to a reward token address. struct Window { // Merkle root describing the distribution. bytes32 merkleRoot; // Currency in which reward is processed. IERC20 rewardToken; // IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical // data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code> // <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier // for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply // go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>. string ipfsHash; } // Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`. struct Claim { uint256 windowIndex; uint256 amount; uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim. address account; bytes32[] merkleProof; } // Windows are mapped to arbitrary indices. mapping(uint256 => Window) public merkleWindows; // Index of next created Merkle root. uint256 public nextCreatedIndex; // Track which accounts have claimed for each window index. // Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract. mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap; /**************************************** * EVENTS ****************************************/ event Claimed( address indexed caller, uint256 windowIndex, address indexed account, uint256 accountIndex, uint256 amount, address indexed rewardToken ); event CreatedWindow( uint256 indexed windowIndex, uint256 rewardsDeposited, address indexed rewardToken, address owner ); event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency); event DeleteWindow(uint256 indexed windowIndex, address owner); /**************************** * ADMIN FUNCTIONS ****************************/ /** * @notice Set merkle root for the next available window index and seed allocations. * @notice Callable only by owner of this contract. Caller must have approved this contract to transfer * `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the * owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all * claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur * because we do not segregate reward balances by window, for code simplicity purposes. * (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must * subsequently transfer in rewards or the following situation can occur). * Example race situation: * - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and * claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101. * - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner * correctly set `rewardsToDeposit` this time. * - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence: * (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens. * (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens. * (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens. * - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would * succeed and the second claim would fail, even though both claimants would expect their claims to succeed. * @param rewardsToDeposit amount of rewards to deposit to seed this allocation. * @param rewardToken ERC20 reward token. * @param merkleRoot merkle root describing allocation. * @param ipfsHash hash of IPFS object, conveniently stored for clients */ function setWindow( uint256 rewardsToDeposit, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) external onlyOwner { uint256 indexToSet = nextCreatedIndex; nextCreatedIndex = indexToSet.add(1); _setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash); } /** * @notice Delete merkle root at window index. * @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state. * @param windowIndex merkle root index to delete. */ function deleteWindow(uint256 windowIndex) external onlyOwner { delete merkleWindows[windowIndex]; emit DeleteWindow(windowIndex, msg.sender); } /** * @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly. * @dev Callable only by owner. * @param rewardCurrency rewards to withdraw from contract. * @param amount amount of rewards to withdraw. */ function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner { IERC20(rewardCurrency).safeTransfer(msg.sender, amount); emit WithdrawRewards(msg.sender, amount, rewardCurrency); } /**************************** * NON-ADMIN FUNCTIONS ****************************/ /** * @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail * if any individual claims within the batch would fail. * @dev Optimistically tries to batch together consecutive claims for the same account and same * reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method * is to pass in an array of claims sorted by account and reward currency. * @param claims array of claims to claim. */ function claimMulti(Claim[] memory claims) external { uint256 batchedAmount = 0; uint256 claimCount = claims.length; for (uint256 i = 0; i < claimCount; i++) { Claim memory _claim = claims[i]; _verifyAndMarkClaimed(_claim); batchedAmount = batchedAmount.add(_claim.amount); // If the next claim is NOT the same account or the same token (or this claim is the last one), // then disburse the `batchedAmount` to the current claim's account for the current claim's reward token. uint256 nextI = i + 1; address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken); if ( nextI == claimCount || // This claim is last claim. claims[nextI].account != _claim.account || // Next claim account is different than current one. address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken // Next claim reward token is different than current one. ) { IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount); batchedAmount = 0; } } } /** * @notice Claim amount of reward tokens for account, as described by Claim input object. * @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the * values stored in the merkle root for the `_claim`'s `windowIndex` this method * will revert. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. */ function claim(Claim memory _claim) public { _verifyAndMarkClaimed(_claim); merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount); } /** * @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at * `windowIndex`. * @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`. * The onus is on the Owner of this contract to submit only valid Merkle roots. * @param windowIndex merkle root to check. * @param accountIndex account index to check within window index. * @return True if claim has been executed already, False otherwise. */ function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /** * @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given * window index. * @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof. * @return valid True if leaf exists. */ function verifyClaim(Claim memory _claim) public view returns (bool valid) { bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex)); return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf); } /**************************** * PRIVATE FUNCTIONS ****************************/ // Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`. function _setClaimed(uint256 windowIndex, uint256 accountIndex) private { uint256 claimedWordIndex = accountIndex / 256; uint256 claimedBitIndex = accountIndex % 256; claimedBitMap[windowIndex][claimedWordIndex] = claimedBitMap[windowIndex][claimedWordIndex] | (1 << claimedBitIndex); } // Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root. function _setWindow( uint256 windowIndex, uint256 rewardsDeposited, address rewardToken, bytes32 merkleRoot, string memory ipfsHash ) private { Window storage window = merkleWindows[windowIndex]; window.merkleRoot = merkleRoot; window.rewardToken = IERC20(rewardToken); window.ipfsHash = ipfsHash; emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender); window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited); } // Verify claim is valid and mark it as completed in this contract. function _verifyAndMarkClaimed(Claim memory _claim) private { // Check claimed proof against merkle window at given index. require(verifyClaim(_claim), "Incorrect merkle proof"); // Check the account has not yet claimed for this window. require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window"); // Proof is correct and claim has not occurred yet, mark claimed complete. _setClaimed(_claim.windowIndex, _claim.accountIndex); emit Claimed( msg.sender, _claim.windowIndex, _claim.account, _claim.accountIndex, _claim.amount, address(merkleWindows[_claim.windowIndex].rewardToken) ); } } pragma solidity ^0.6.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; import "../common/FundingRateApplier.sol"; /** * @title Financial contract with priceless position management. * @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying * on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token. */ contract PerpetualPositionManager is FundingRateApplier { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; using SafeERC20 for ExpandedIERC20; /**************************************** * PRICELESS POSITION DATA STRUCTURES * ****************************************/ // Represents a single sponsor's position. All collateral is held by this contract. // This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor. struct PositionData { FixedPoint.Unsigned tokensOutstanding; // Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`. uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps sponsor addresses to their positions. Each sponsor can have only one position. mapping(address => PositionData) public positions; // Keep track of the total collateral and tokens across all positions to enable calculating the // global collateralization ratio without iterating over all positions. FixedPoint.Unsigned public totalTokensOutstanding; // Similar to the rawCollateral in PositionData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned public rawTotalPositionCollateral; // Synthetic token created by this contract. ExpandedIERC20 public tokenCurrency; // Unique identifier for DVM price feed ticker. bytes32 public priceIdentifier; // Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur. // !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract. // Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests // expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent // contract is extremely risky for any sponsor or synthetic token holder for the contract. uint256 public withdrawalLiveness; // Minimum number of tokens in a sponsor's position. FixedPoint.Unsigned public minSponsorTokens; // Expiry price pulled from the DVM in the case of an emergency shutdown. FixedPoint.Unsigned public emergencyShutdownPrice; /**************************************** * EVENTS * ****************************************/ event Deposit(address indexed sponsor, uint256 indexed collateralAmount); event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount); event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount); event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event NewSponsor(address indexed sponsor); event EndedSponsorPosition(address indexed sponsor); event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount); event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount); event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp); event SettleEmergencyShutdown( address indexed caller, uint256 indexed collateralReturned, uint256 indexed tokensBurned ); /**************************************** * MODIFIERS * ****************************************/ modifier onlyCollateralizedPosition(address sponsor) { _onlyCollateralizedPosition(sponsor); _; } modifier noPendingWithdrawal(address sponsor) { _positionHasNoPendingWithdrawal(sponsor); _; } /** * @notice Construct the PerpetualPositionManager. * @dev Deployer of this contract should consider carefully which parties have ability to mint and burn * the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts * can mint new tokens, which could be used to steal all of this contract's locked collateral. * We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles) * is assigned to this contract, whose sole Minter role is assigned to this contract, and whose * total supply is 0 prior to construction of this contract. * @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals. * @param _collateralAddress ERC20 token used as collateral for all positions. * @param _tokenAddress ERC20 token used as synthetic token. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM for the synthetic. * @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract. * @param _minSponsorTokens minimum number of tokens that must exist at any time in a position. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production. */ constructor( uint256 _withdrawalLiveness, address _collateralAddress, address _tokenAddress, address _finderAddress, bytes32 _priceIdentifier, bytes32 _fundingRateIdentifier, FixedPoint.Unsigned memory _minSponsorTokens, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier)); withdrawalLiveness = _withdrawalLiveness; tokenCurrency = ExpandedIERC20(_tokenAddress); minSponsorTokens = _minSponsorTokens; priceIdentifier = _priceIdentifier; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param sponsor the sponsor to credit the deposit to. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(sponsor) fees() nonReentrant() { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(sponsor); // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); emit Deposit(sponsor, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position. * @dev Increases the collateralization level of a position after creation. This contract must be approved to spend * at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public { // This is just a thin wrapper over depositTo that specified the sender as the sponsor. depositTo(msg.sender, collateralAmount); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor. * @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization * ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss. * @param collateralAmount is the amount of collateral to withdraw. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdraw(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { require(collateralAmount.isGreaterThan(0)); PositionData storage positionData = _getPositionData(msg.sender); // Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure // position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request. amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount); emit Withdrawal(msg.sender, amountWithdrawn.rawValue); // Move collateral currency from contract to sender. // Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees) // instead of the user requested amount. This eliminates precision loss that could occur // where the user withdraws more collateral than rawCollateral is decremented by. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position. * @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated. * @param collateralAmount the amount of collateral requested to withdraw */ function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require( collateralAmount.isGreaterThan(0) && collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral)) ); // Update the position object for the user. positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); positionData.withdrawalRequestAmount = collateralAmount; emit RequestWithdrawal(msg.sender, collateralAmount.rawValue); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting * `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function withdrawPassedRequest() external notEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require( positionData.withdrawalRequestPassTimestamp != 0 && positionData.withdrawalRequestPassTimestamp <= getCurrentTime() ); // If withdrawal request amount is > position collateral, then withdraw the full collateral amount. // This situation is possible due to fees charged since the withdrawal was originally requested. FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount; if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) { amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral); } // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); // No pending withdrawal require message removed to save bytecode. require(positionData.withdrawalRequestPassTimestamp != 0); emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue); // Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0. _resetWithdrawalRequest(positionData); } /** * @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount * ` into the sponsor's position and mints `numTokens` of `tokenCurrency`. * @dev This contract must have the Minter role for the `tokenCurrency`. * @dev Reverts if minting these tokens would put the position's collateralization ratio below the * global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of * `collateralCurrency`. * @param collateralAmount is the number of collateral tokens to collateralize the position with * @param numTokens is the number of tokens to mint from the position. */ function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() fees() nonReentrant() { PositionData storage positionData = positions[msg.sender]; // Either the new create ratio or the resultant position CR must be above the current GCR. require( (_checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount), positionData.tokensOutstanding.add(numTokens) ) || _checkCollateralization(collateralAmount, numTokens)), "Insufficient collateral" ); require(positionData.withdrawalRequestPassTimestamp == 0); if (positionData.tokensOutstanding.isEqual(0)) { require(numTokens.isGreaterThanOrEqual(minSponsorTokens)); emit NewSponsor(msg.sender); } // Increase the position and global collateral balance by collateral amount. _incrementCollateralBalances(positionData, collateralAmount); // Add the number of tokens created to the position's outstanding tokens. positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens); totalTokensOutstanding = totalTokensOutstanding.add(numTokens); emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue); // Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); // Note: revert reason removed to save bytecode. require(tokenCurrency.mint(msg.sender, numTokens.rawValue)); } /** * @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`. * @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral * in order to account for precision loss. This contract must be approved to spend at least `numTokens` of * `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function redeem(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding); FixedPoint.Unsigned memory collateralRedeemed = fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral)); // If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize. if (positionData.tokensOutstanding.isEqual(numTokens)) { amountWithdrawn = _deleteSponsorPosition(msg.sender); } else { // Decrement the sponsor's collateral and global collateral amounts. amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); } emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue); // Transfer collateral from contract to caller and burn callers synthetic tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`. * This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens. * @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param numTokens is the number of tokens to be burnt from the sponsor's debt position. */ function repay(FixedPoint.Unsigned memory numTokens) public notEmergencyShutdown() noPendingWithdrawal(msg.sender) fees() nonReentrant() { PositionData storage positionData = _getPositionData(msg.sender); require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding)); // Decrease the sponsors position tokens size. Ensure it is above the min sponsor size. FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens); require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens)); positionData.tokensOutstanding = newTokenCount; // Update the totalTokensOutstanding after redemption. totalTokensOutstanding = totalTokensOutstanding.sub(numTokens); emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue); // Transfer the tokens back from the sponsor and burn them. tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue); tokenCurrency.burn(numTokens.rawValue); } /** * @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or * remaining collateral for underlying at the prevailing price defined by a DVM vote. * @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of * `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for * precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance. * @dev This contract must have the Burner role for the `tokenCurrency`. * @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this * function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown. * @return amountWithdrawn The actual amount of collateral withdrawn. */ function settleEmergencyShutdown() external isEmergencyShutdown() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { // Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert. if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) { emergencyShutdownPrice = _getOracleEmergencyShutdownPrice(); } // Get caller's tokens balance and calculate amount of underlying entitled to them. FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender)); FixedPoint.Unsigned memory totalRedeemableCollateral = _getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice); // If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt. PositionData storage positionData = positions[msg.sender]; if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) { // Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with // the funding rate applied to the outstanding token debt. FixedPoint.Unsigned memory tokenDebtValueInCollateral = _getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice); FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral); // If the debt is greater than the remaining collateral, they cannot redeem anything. FixedPoint.Unsigned memory positionRedeemableCollateral = tokenDebtValueInCollateral.isLessThan(positionCollateral) ? positionCollateral.sub(tokenDebtValueInCollateral) : FixedPoint.Unsigned(0); // Add the number of redeemable tokens for the sponsor to their total redeemable collateral. totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral); // Reset the position state as all the value has been removed after settlement. delete positions[msg.sender]; emit EndedSponsorPosition(msg.sender); } // Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized, // the caller will get as much collateral as the contract can pay out. FixedPoint.Unsigned memory payout = FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral); // Decrement total contract collateral and outstanding debt. amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout); totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem); emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue); // Transfer tokens & collateral and burn the redeemed tokens. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue); tokenCurrency.burn(tokensToRedeem.rawValue); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ /** * @notice Premature contract settlement under emergency circumstances. * @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`. * Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal * to occur via the `settleEmergencyShutdown` function. */ function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() { // Note: revert reason removed to save bytecode. require(msg.sender == _getFinancialContractsAdminAddress()); emergencyShutdownTimestamp = getCurrentTime(); _requestOraclePrice(emergencyShutdownTimestamp); emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp); } /** * @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they * reflect the NAV of the contract. However, this functionality doesn't apply to this contract. * @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable * only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing. */ function remargin() external override { return; } /** * @notice Accessor method for a sponsor's collateral. * @dev This is necessary because the struct returned by the positions() method shows * rawCollateral, which isn't a user-readable value. * @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for * example if the `lastPaymentTime != currentTime`. * @param sponsor address whose collateral amount is retrieved. * @return collateralAmount amount of collateral within a sponsors position. */ function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory collateralAmount) { // Note: do a direct access to avoid the validity check. return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral)); } /** * @notice Accessor method for the total collateral stored within the PerpetualPositionManager. * @return totalCollateral amount of all collateral within the position manager. */ function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) external view nonReentrantView() returns (FixedPoint.Unsigned memory totalCollateral) { return _getFundingRateAppliedTokenDebt(rawTokenDebt); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire // position if the entire position is being removed. Does not make any external transfers. function _reduceSponsorPosition( address sponsor, FixedPoint.Unsigned memory tokensToRemove, FixedPoint.Unsigned memory collateralToRemove, FixedPoint.Unsigned memory withdrawalAmountToRemove ) internal { PositionData storage positionData = _getPositionData(sponsor); // If the entire position is being removed, delete it instead. if ( tokensToRemove.isEqual(positionData.tokensOutstanding) && _getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove) ) { _deleteSponsorPosition(sponsor); return; } // Decrement the sponsor's collateral and global collateral amounts. _decrementCollateralBalances(positionData, collateralToRemove); // Ensure that the sponsor will meet the min position size after the reduction. positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove); require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens)); // Decrement the position's withdrawal amount. positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove); // Decrement the total outstanding tokens in the overall contract. totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove); } // Deletes a sponsor's position and updates global counters. Does not make any external transfers. function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) { PositionData storage positionToLiquidate = _getPositionData(sponsor); FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral); // Remove the collateral and outstanding from the overall total position. rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral); totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding); // Reset the sponsors position to have zero outstanding and collateral. delete positions[sponsor]; emit EndedSponsorPosition(sponsor); // Return fee-adjusted amount of collateral deleted from position. return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral)); } function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalPositionCollateral); } function _getPositionData(address sponsor) internal view onlyCollateralizedPosition(sponsor) returns (PositionData storage) { return positions[sponsor]; } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } function _getFinancialContractsAdminAddress() internal view returns (address) { return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin); } // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { _getOracle().requestPrice(priceIdentifier, requestedTime); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) { // Create an instance of the oracle and get the price. If the price is not resolved revert. int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime); // For now we don't want to deal with negative prices in positions. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) { return _getOraclePrice(emergencyShutdownTimestamp); } // Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0. function _resetWithdrawalRequest(PositionData storage positionData) internal { positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); positionData.withdrawalRequestPassTimestamp = 0; } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(positionData.rawCollateral, collateralAmount); return _addCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position. // This function is similar to the _decrementCollateralBalances function except this function checks position GCR // between the decrements. This ensures that collateral removal will not leave the position undercollateralized. function _decrementCollateralBalancesCheckGCR( PositionData storage positionData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(positionData.rawCollateral, collateralAmount); require(_checkPositionCollateralization(positionData), "CR below GCR"); return _removeCollateral(rawTotalPositionCollateral, collateralAmount); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _onlyCollateralizedPosition(address sponsor) internal view { require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0)); } // Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the // `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral // or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`. function _positionHasNoPendingWithdrawal(address sponsor) internal view { require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0); } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) { return _checkCollateralization( _getFeeAdjustedCollateral(positionData.rawCollateral), positionData.tokensOutstanding ); } // Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global // collateralization ratio. function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private view returns (bool) { FixedPoint.Unsigned memory global = _getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding); FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens); return !global.isGreaterThan(thisChange); } function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens) private pure returns (FixedPoint.Unsigned memory ratio) { return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens); } function _getTokenAddress() internal view override returns (address) { return address(tokenCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/implementation/Testable.sol"; import "../../oracle/implementation/Constants.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../perpetual-multiparty/ConfigStoreInterface.sol"; import "./EmergencyShutdownable.sol"; import "./FeePayer.sol"; /** * @title FundingRateApplier contract. * @notice Provides funding rate payment functionality for the Perpetual contract. */ abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; using SafeERC20 for IERC20; using SafeMath for uint256; /**************************************** * FUNDING RATE APPLIER DATA STRUCTURES * ****************************************/ struct FundingRate { // Current funding rate value. FixedPoint.Signed rate; // Identifier to retrieve the funding rate. bytes32 identifier; // Tracks the cumulative funding payments that have been paid to the sponsors. // The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment). // Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ... // For example: // The cumulativeFundingRateMultiplier should start at 1. // If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01. // If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201). FixedPoint.Unsigned cumulativeMultiplier; // Most recent time that the funding rate was updated. uint256 updateTime; // Most recent time that the funding rate was applied and changed the cumulative multiplier. uint256 applicationTime; // The time for the active (if it exists) funding rate proposal. 0 otherwise. uint256 proposalTime; } FundingRate public fundingRate; // Remote config store managed an owner. ConfigStoreInterface public configStore; /**************************************** * EVENTS * ****************************************/ event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward); /**************************************** * MODIFIERS * ****************************************/ // This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate. modifier fees override { // Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the // rate applied linearly since the last update. This implies that the compounding rate depends on the frequency // of update transactions that have this modifier, and it never reaches the ideal of continuous compounding. // This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of // compounding data on-chain. applyFundingRate(); _; } // Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees. modifier paysRegularFees { payRegularFees(); _; } /** * @notice Constructs the FundingRateApplier contract. Called by child contracts. * @param _fundingRateIdentifier identifier that tracks the funding rate of this contract. * @param _collateralAddress address of the collateral token. * @param _finderAddress Finder used to discover financial-product-related contracts. * @param _configStoreAddress address of the remote configuration store managed by an external owner. * @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index). * @param _timerAddress address of the timer contract in test envs, otherwise 0x0. */ constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() { uint256 currentTime = getCurrentTime(); fundingRate.updateTime = currentTime; fundingRate.applicationTime = currentTime; // Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are // applied over time. fundingRate.cumulativeMultiplier = _tokenScaling; fundingRate.identifier = _fundingRateIdentifier; configStore = ConfigStoreInterface(_configStoreAddress); } /** * @notice This method takes 3 distinct actions: * 1. Pays out regular fees. * 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards. * 3. Applies the prevailing funding rate over the most recent period. */ function applyFundingRate() public paysRegularFees() nonReentrant() { _applyEffectiveFundingRate(); } /** * @notice Proposes a new funding rate. Proposer receives a reward if correct. * @param rate funding rate being proposed. * @param timestamp time at which the funding rate was computed. */ function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp) external fees() nonReentrant() returns (FixedPoint.Unsigned memory totalBond) { require(fundingRate.proposalTime == 0, "Proposal in progress"); _validateFundingRate(rate); // Timestamp must be after the last funding rate update time, within the last 30 minutes. uint256 currentTime = getCurrentTime(); uint256 updateTime = fundingRate.updateTime; require( timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit), "Invalid proposal time" ); // Set the proposal time in order to allow this contract to track this request. fundingRate.proposalTime = timestamp; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Set up optimistic oracle. bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Note: requestPrice will revert if `timestamp` is less than the current block timestamp. optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0); totalBond = FixedPoint.Unsigned( optimisticOracle.setBond( identifier, timestamp, ancillaryData, _pfc().mul(_getConfig().proposerBondPercentage).rawValue ) ); // Pull bond from caller and send to optimistic oracle. if (totalBond.isGreaterThan(0)) { collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue); collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue); } optimisticOracle.proposePriceFor( msg.sender, address(this), identifier, timestamp, ancillaryData, rate.rawValue ); } // Returns a token amount scaled by the current funding rate multiplier. // Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value. function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt) internal view returns (FixedPoint.Unsigned memory tokenDebt) { return rawTokenDebt.mul(fundingRate.cumulativeMultiplier); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) { return configStore.updateAndGetCurrentConfig(); } function _updateFundingRate() internal { uint256 proposalTime = fundingRate.proposalTime; // If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate. if (proposalTime != 0) { // Attempt to update the funding rate. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); bytes32 identifier = fundingRate.identifier; bytes memory ancillaryData = _getAncillaryData(); // Try to get the price from the optimistic oracle. This call will revert if the request has not resolved // yet. If the request has not resolved yet, then we need to do additional checks to see if we should // "forget" the pending proposal and allow new proposals to update the funding rate. try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) { // If successful, determine if the funding rate state needs to be updated. // If the request is more recent than the last update then we should update it. uint256 lastUpdateTime = fundingRate.updateTime; if (proposalTime >= lastUpdateTime) { // Update funding rates fundingRate.rate = FixedPoint.Signed(price); fundingRate.updateTime = proposalTime; // If there was no dispute, send a reward. FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0); OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer == address(0)) { reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime)); if (reward.isGreaterThan(0)) { _adjustCumulativeFeeMultiplier(reward, _pfc()); collateralCurrency.safeTransfer(request.proposer, reward.rawValue); } } // This event will only be emitted after the fundingRate struct's "updateTime" has been set // to the latest proposal's proposalTime, indicating that the proposal has been published. // So, it suffices to just emit fundingRate.updateTime here. emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue); } // Set proposal time to 0 since this proposal has now been resolved. fundingRate.proposalTime = 0; } catch { // Stop tracking and allow other proposals to come in if: // - The requester address is empty, indicating that the Oracle does not know about this funding rate // request. This is possible if the Oracle is replaced while the price request is still pending. // - The request has been disputed. OptimisticOracleInterface.Request memory request = optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData); if (request.disputer != address(0) || request.proposer == address(0)) { fundingRate.proposalTime = 0; } } } } // Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the // perpetual's security. For example, let's examine the case where the max and min funding rates // are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a // proposer who can deter honest proposers for 74 hours: // 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%. // How would attack work? Imagine that the market is very volatile currently and that the "true" funding // rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500% // (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding // rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value. function _validateFundingRate(FixedPoint.Signed memory rate) internal { require( rate.isLessThanOrEqual(_getConfig().maxFundingRate) && rate.isGreaterThanOrEqual(_getConfig().minFundingRate) ); } // Fetches a funding rate from the Store, determines the period over which to compute an effective fee, // and multiplies the current multiplier by the effective fee. // A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier. // Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat // values < 1 as "negative". function _applyEffectiveFundingRate() internal { // If contract is emergency shutdown, then the funding rate multiplier should no longer change. if (emergencyShutdownTimestamp != 0) { return; } uint256 currentTime = getCurrentTime(); uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime); _updateFundingRate(); // Update the funding rate if there is a resolved proposal. fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate( paymentPeriod, fundingRate.rate, fundingRate.cumulativeMultiplier ); fundingRate.applicationTime = currentTime; } function _calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) { // Note: this method uses named return variables to save a little bytecode. // The overall formula that this function is performing: // newCumulativeFundingRateMultiplier = // (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier. FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1); // Multiply the per-second rate over the number of seconds that have elapsed to get the period rate. FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds)); // Add one to create the multiplier to scale the existing fee multiplier. FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate); // Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned. FixedPoint.Unsigned memory unsignedPeriodMultiplier = FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0))); // Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new // cumulative funding rate multiplier. newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier); } function _getAncillaryData() internal view returns (bytes memory) { // Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address // whose funding rate it's trying to get. return abi.encodePacked(_getTokenAddress()); } function _getTokenAddress() internal view virtual returns (address); } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such 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. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; interface ConfigStoreInterface { // All of the configuration settings available for querying by a perpetual. struct ConfigSettings { // Liveness period (in seconds) for an update to currentConfig to become official. uint256 timelockLiveness; // Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%. FixedPoint.Unsigned rewardRatePerSecond; // Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%. FixedPoint.Unsigned proposerBondPercentage; // Maximum funding rate % per second that can be proposed. FixedPoint.Signed maxFundingRate; // Minimum funding rate % per second that can be proposed. FixedPoint.Signed minFundingRate; // Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest // update time. uint256 proposalTimePastLimit; } function updateAndGetCurrentConfig() external returns (ConfigSettings memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title EmergencyShutdownable contract. * @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable. * This contract provides modifiers that can be used by children contracts to determine if the contract is * in the shutdown state. The child contract is expected to implement the logic that happens * once a shutdown occurs. */ abstract contract EmergencyShutdownable { using SafeMath for uint256; /**************************************** * EMERGENCY SHUTDOWN DATA STRUCTURES * ****************************************/ // Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered. uint256 public emergencyShutdownTimestamp; /**************************************** * MODIFIERS * ****************************************/ modifier notEmergencyShutdown() { _notEmergencyShutdown(); _; } modifier isEmergencyShutdown() { _isEmergencyShutdown(); _; } /**************************************** * EXTERNAL FUNCTIONS * ****************************************/ constructor() public { emergencyShutdownTimestamp = 0; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _notEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp == 0); } function _isEmergencyShutdown() internal view { // Note: removed require string to save bytecode. require(emergencyShutdownTimestamp != 0); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../common/FundingRateApplier.sol"; import "../../common/implementation/FixedPoint.sol"; // Implements FundingRateApplier internal methods to enable unit testing. contract FundingRateApplierTest is FundingRateApplier { constructor( bytes32 _fundingRateIdentifier, address _collateralAddress, address _finderAddress, address _configStoreAddress, FixedPoint.Unsigned memory _tokenScaling, address _timerAddress ) public FundingRateApplier( _fundingRateIdentifier, _collateralAddress, _finderAddress, _configStoreAddress, _tokenScaling, _timerAddress ) {} function calculateEffectiveFundingRate( uint256 paymentPeriodSeconds, FixedPoint.Signed memory fundingRatePerSecond, FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier ) public pure returns (FixedPoint.Unsigned memory) { return _calculateEffectiveFundingRate( paymentPeriodSeconds, fundingRatePerSecond, currentCumulativeFundingRateMultiplier ); } // Required overrides. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) { return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this))); } function emergencyShutdown() external override {} function remargin() external override {} function _getTokenAddress() internal view override returns (address) { return address(collateralCurrency); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ConfigStoreInterface.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it * to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded * by a privileged account and the upgraded changes are timelocked. */ contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /**************************************** * STORE DATA STRUCTURES * ****************************************/ // Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig // if its liveness has expired. ConfigStoreInterface.ConfigSettings private currentConfig; // Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config. ConfigStoreInterface.ConfigSettings public pendingConfig; uint256 public pendingPassedTimestamp; /**************************************** * EVENTS * ****************************************/ event ProposedNewConfigSettings( address indexed proposer, uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit, uint256 proposalPassedTimestamp ); event ChangedConfigSettings( uint256 rewardRatePerSecond, uint256 proposerBondPercentage, uint256 timelockLiveness, int256 maxFundingRate, int256 minFundingRate, uint256 proposalTimePastLimit ); /**************************************** * MODIFIERS * ****************************************/ // Update config settings if possible. modifier updateConfig() { _updateConfig(); _; } /** * @notice Construct the Config Store. An initial configuration is provided and set on construction. * @param _initialConfig Configuration settings to initialize `currentConfig` with. * @param _timerAddress Address of testable Timer contract. */ constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) { _validateConfig(_initialConfig); currentConfig = _initialConfig; } /** * @notice Returns current config or pending config if pending liveness has expired. * @return ConfigSettings config settings that calling financial contract should view as "live". */ function updateAndGetCurrentConfig() external override updateConfig() nonReentrant() returns (ConfigStoreInterface.ConfigSettings memory) { return currentConfig; } /** * @notice Propose new configuration settings. New settings go into effect after a liveness period passes. * @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now. * @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal. */ function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() { _validateConfig(newConfig); // Warning: This overwrites a pending proposal! pendingConfig = newConfig; // Use current config's liveness period to timelock this proposal. pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness); emit ProposedNewConfigSettings( msg.sender, newConfig.rewardRatePerSecond.rawValue, newConfig.proposerBondPercentage.rawValue, newConfig.timelockLiveness, newConfig.maxFundingRate.rawValue, newConfig.minFundingRate.rawValue, newConfig.proposalTimePastLimit, pendingPassedTimestamp ); } /** * @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness. */ function publishPendingConfig() external nonReentrant() updateConfig() {} /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Check if pending proposal can overwrite the current config. function _updateConfig() internal { // If liveness has passed, publish proposed configuration settings. if (_pendingProposalPassed()) { currentConfig = pendingConfig; _deletePendingConfig(); emit ChangedConfigSettings( currentConfig.rewardRatePerSecond.rawValue, currentConfig.proposerBondPercentage.rawValue, currentConfig.timelockLiveness, currentConfig.maxFundingRate.rawValue, currentConfig.minFundingRate.rawValue, currentConfig.proposalTimePastLimit ); } } function _deletePendingConfig() internal { delete pendingConfig; pendingPassedTimestamp = 0; } function _pendingProposalPassed() internal view returns (bool) { return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime()); } // Use this method to constrain values with which you can set ConfigSettings. function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure { // We don't set limits on proposal timestamps because there are already natural limits: // - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints. // - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30 // mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time. // Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself // before a vulnerability drains its collateral. require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness"); // The reward rate should be modified as needed to incentivize honest proposers appropriately. // Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs // = 0.0000033 FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7); require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond"); // We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer // were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer // could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest // proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their // PfC for each proposal liveness window. The downside of not limiting this is that the config store owner // can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the // proposal bond based on the configuration's funding rate range like in this discussion: // https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383 // We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude // funding rates in extraordinarily volatile market situations. Note, that even though we do not bound // the max/min, we still recommend that the deployer of this contract set the funding rate max/min values // to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year]. } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./PerpetualLib.sol"; import "./ConfigStore.sol"; /** * @title Perpetual Contract creator. * @notice Factory contract to create and register new instances of perpetual contracts. * Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints * that are applied to newly created contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract PerpetualCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * PERP CREATOR DATA STRUCTURES * ****************************************/ // Immutable params for perpetual contract. struct Params { address collateralAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; uint256 withdrawalLiveness; uint256 liquidationLiveness; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress); event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress); /** * @notice Constructs the Perpetual contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of perpetual and registers it within the registry. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed contract. */ function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); // Create new config settings store for this contract and reset ownership to the deployer. ConfigStore configStore = new ConfigStore(configSettings, timerAddress); configStore.transferOwnership(msg.sender); emit CreatedConfigStore(address(configStore), configStore.owner()); // Create a new synthetic token using the params. TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, // then a default precision of 18 will be applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore))); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedPerpetual(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createPerpetual params to Perpetual constructor params. function _convertParams( Params memory params, ExpandedIERC20 newTokenCurrency, address configStore ) private view returns (Perpetual.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want perpetual deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the perpetual unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // To avoid precision loss or overflows, prevent the token scaling from being too large or too small. FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10 FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10 require( params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling), "Invalid tokenScaling" ); // Input from function call. constructorParams.configStoreAddress = configStore; constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.fundingRateIdentifier = params.fundingRateIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.tokenScaling = params.tokenScaling; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/FinderInterface.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "./Registry.sol"; import "./Constants.sol"; /** * @title Base contract for all financial contract creators */ abstract contract ContractCreator { address internal finderAddress; constructor(address _finderAddress) public { finderAddress = _finderAddress; } function _requireWhitelistedCollateral(address collateralAddress) internal view { FinderInterface finder = FinderInterface(finderAddress); AddressWhitelist collateralWhitelist = AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted"); } function _registerContract(address[] memory parties, address contractToRegister) internal { FinderInterface finder = FinderInterface(finderAddress); Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry)); registry.registerContract(parties, contractToRegister); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "./SyntheticToken.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Factory for creating new mintable and burnable tokens. */ contract TokenFactory is Lockable { /** * @notice Create a new token and return it to the caller. * @dev The caller will become the only minter and burner and the new owner capable of assigning the roles. * @param tokenName used to describe the new token. * @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals used to define the precision used in the token's numerical representation. * @return newToken an instance of the newly created token interface. */ function createToken( string calldata tokenName, string calldata tokenSymbol, uint8 tokenDecimals ) external nonReentrant() returns (ExpandedIERC20 newToken) { SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals); mintableToken.addMinter(msg.sender); mintableToken.addBurner(msg.sender); mintableToken.resetOwner(msg.sender); newToken = ExpandedIERC20(address(mintableToken)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../common/implementation/ExpandedERC20.sol"; import "../../common/implementation/Lockable.sol"; /** * @title Burnable and mintable ERC20. * @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles. */ contract SyntheticToken is ExpandedERC20, Lockable { /** * @notice Constructs the SyntheticToken. * @param tokenName The name which describes the new token. * @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars. * @param tokenDecimals The number of decimals to define token precision. */ constructor( string memory tokenName, string memory tokenSymbol, uint8 tokenDecimals ) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {} /** * @notice Add Minter role to account. * @dev The caller must have the Owner role. * @param account The address to which the Minter role is added. */ function addMinter(address account) external override nonReentrant() { addMember(uint256(Roles.Minter), account); } /** * @notice Remove Minter role from account. * @dev The caller must have the Owner role. * @param account The address from which the Minter role is removed. */ function removeMinter(address account) external nonReentrant() { removeMember(uint256(Roles.Minter), account); } /** * @notice Add Burner role to account. * @dev The caller must have the Owner role. * @param account The address to which the Burner role is added. */ function addBurner(address account) external override nonReentrant() { addMember(uint256(Roles.Burner), account); } /** * @notice Removes Burner role from account. * @dev The caller must have the Owner role. * @param account The address from which the Burner role is removed. */ function removeBurner(address account) external nonReentrant() { removeMember(uint256(Roles.Burner), account); } /** * @notice Reset Owner role to account. * @dev The caller must have the Owner role. * @param account The new holder of the Owner role. */ function resetOwner(address account) external override nonReentrant() { resetMember(uint256(Roles.Owner), account); } /** * @notice Checks if a given account holds the Minter role. * @param account The address which is checked for the Minter role. * @return bool True if the provided account is a Minter. */ function isMinter(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Minter), account); } /** * @notice Checks if a given account holds the Burner role. * @param account The address which is checked for the Burner role. * @return bool True if the provided account is a Burner. */ function isBurner(address account) public view nonReentrantView() returns (bool) { return holdsRole(uint256(Roles.Burner), account); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Perpetual.sol"; /** * @title Provides convenient Perpetual Multi Party contract utilities. * @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode. */ library PerpetualLib { /** * @notice Returns address of new Perpetual deployed with given `params` configuration. * @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from Perpetual. * @return address of the deployed Perpetual contract */ function deploy(Perpetual.ConstructorParams memory params) public returns (address) { Perpetual derivative = new Perpetual(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./PerpetualLiquidatable.sol"; /** * @title Perpetual Multiparty Contract. * @notice Convenient wrapper for Liquidatable. */ contract Perpetual is PerpetualLiquidatable { /** * @notice Constructs the Perpetual contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualLiquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./PerpetualPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title PerpetualLiquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract PerpetualLiquidatable is PerpetualPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PerpetualPositionManager only. uint256 withdrawalLiveness; address configStoreAddress; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; bytes32 priceFeedIdentifier; bytes32 fundingRateIdentifier; FixedPoint.Unsigned minSponsorTokens; FixedPoint.Unsigned tokenScaling; // Params specifically for PerpetualLiquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PerpetualPositionManager( params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.fundingRateIdentifier, params.minSponsorTokens, params.configStoreAddress, params.tokenScaling, params.timerAddress ) { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external notEmergencyShutdown() fees() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position // are not funding-rate adjusted because the multiplier only affects their redemption value, not their // notional. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated), lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, _getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final * fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePrice(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. // Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at // liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in // the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement); // If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)) ); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../common/interfaces/IERC20Standard.sol"; import "../../oracle/implementation/ContractCreator.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/AddressWhitelist.sol"; import "../../common/implementation/Lockable.sol"; import "../common/TokenFactory.sol"; import "../common/SyntheticToken.sol"; import "./ExpiringMultiPartyLib.sol"; /** * @title Expiring Multi Party Contract creator. * @notice Factory contract to create and register new instances of expiring multiparty contracts. * Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints * that are applied to newly created expiring multi party contract. These constraints can evolve over time and are * initially constrained to conservative values in this first iteration. Technically there is nothing in the * ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended * to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract), we can enforce deployment configurations here. */ contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; /**************************************** * EMP CREATOR DATA STRUCTURES * ****************************************/ struct Params { uint256 expirationTimestamp; address collateralAddress; bytes32 priceFeedIdentifier; string syntheticName; string syntheticSymbol; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; FixedPoint.Unsigned minSponsorTokens; uint256 withdrawalLiveness; uint256 liquidationLiveness; address financialProductLibraryAddress; } // Address of TokenFactory used to create a new synthetic token. address public tokenFactoryAddress; event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress); /** * @notice Constructs the ExpiringMultiPartyCreator contract. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances. * @param _timerAddress Contract that stores the current time in a testing environment. */ constructor( address _finderAddress, address _tokenFactoryAddress, address _timerAddress ) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() { tokenFactoryAddress = _tokenFactoryAddress; } /** * @notice Creates an instance of expiring multi party and registers it within the registry. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract. */ function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { // Create a new synthetic token using the params. require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); // If the collateral token does not have a `decimals()` method, then a default precision of 18 will be // applied to the newly created synthetic token. uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); // Give permissions to new derivative contract and then hand over ownership. tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; } /**************************************** * PRIVATE FUNCTIONS * ****************************************/ // Converts createExpiringMultiParty params to ExpiringMultiParty constructor params. function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency) private view returns (ExpiringMultiParty.ConstructorParams memory constructorParams) { // Known from creator deployment. constructorParams.finderAddress = finderAddress; constructorParams.timerAddress = timerAddress; // Enforce configuration constraints. require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0"); require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0"); require(params.expirationTimestamp > now, "Invalid expiration time"); _requireWhitelistedCollateral(params.collateralAddress); // We don't want EMP deployers to be able to intentionally or unintentionally set // liveness periods that could induce arithmetic overflow, but we also don't want // to be opinionated about what livenesses are "correct", so we will somewhat // arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness // periods even greater than a few days would make the EMP unusable for most users. require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large"); require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large"); // Input from function call. constructorParams.tokenAddress = address(newTokenCurrency); constructorParams.expirationTimestamp = params.expirationTimestamp; constructorParams.collateralAddress = params.collateralAddress; constructorParams.priceFeedIdentifier = params.priceFeedIdentifier; constructorParams.collateralRequirement = params.collateralRequirement; constructorParams.disputeBondPercentage = params.disputeBondPercentage; constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; constructorParams.minSponsorTokens = params.minSponsorTokens; constructorParams.withdrawalLiveness = params.withdrawalLiveness; constructorParams.liquidationLiveness = params.liquidationLiveness; constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress; } // IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method, // which is possible since the method is only an OPTIONAL method in the ERC20 standard: // https://eips.ethereum.org/EIPS/eip-20#methods. function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) { try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) { return _decimals; } catch { return 18; } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ExpiringMultiParty.sol"; /** * @title Provides convenient Expiring Multi Party contract utilities. * @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode. */ library ExpiringMultiPartyLib { /** * @notice Returns address of new EMP deployed with given `params` configuration. * @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also * responsible for enforcing constraints on `params`. * @param params is a `ConstructorParams` object from ExpiringMultiParty. * @return address of the deployed ExpiringMultiParty contract */ function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) { ExpiringMultiParty derivative = new ExpiringMultiParty(params); return address(derivative); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Liquidatable.sol"; /** * @title Expiring Multi Party. * @notice Convenient wrapper for Liquidatable. */ contract ExpiringMultiParty is Liquidatable { /** * @notice Constructs the ExpiringMultiParty contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public Liquidatable(params) // Note: since there is no logic here, there is no need to add a re-entrancy guard. { } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./PricelessPositionManager.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title Liquidatable * @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position. * @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the * liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on * a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false * liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a * prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute. * NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on * transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing * money themselves). */ contract Liquidatable is PricelessPositionManager { using FixedPoint for FixedPoint.Unsigned; using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; /**************************************** * LIQUIDATION DATA STRUCTURES * ****************************************/ // Because of the check in withdrawable(), the order of these enum values should not change. enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed } struct LiquidationData { // Following variables set upon creation of liquidation: address sponsor; // Address of the liquidated position's sponsor address liquidator; // Address who created this liquidation Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle // Following variables determined by the position that is being liquidated: FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute // Amount of collateral being liquidated, which could be different from // lockedCollateral if there were pending withdrawals at the time of liquidation FixedPoint.Unsigned liquidatedCollateral; // Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation. FixedPoint.Unsigned rawUnitCollateral; // Following variable set upon initiation of a dispute: address disputer; // Person who is disputing a liquidation // Following variable set upon a resolution of a dispute: FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute FixedPoint.Unsigned finalFee; } // Define the contract's constructor parameters as a struct to enable more variables to be specified. // This is required to enable more params, over and above Solidity's limits. struct ConstructorParams { // Params for PricelessPositionManager only. uint256 expirationTimestamp; uint256 withdrawalLiveness; address collateralAddress; address tokenAddress; address finderAddress; address timerAddress; address financialProductLibraryAddress; bytes32 priceFeedIdentifier; FixedPoint.Unsigned minSponsorTokens; // Params specifically for Liquidatable. uint256 liquidationLiveness; FixedPoint.Unsigned collateralRequirement; FixedPoint.Unsigned disputeBondPercentage; FixedPoint.Unsigned sponsorDisputeRewardPercentage; FixedPoint.Unsigned disputerDisputeRewardPercentage; } // This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards. // `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ // from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the // fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error. struct RewardsData { FixedPoint.Unsigned payToSponsor; FixedPoint.Unsigned payToLiquidator; FixedPoint.Unsigned payToDisputer; FixedPoint.Unsigned paidToSponsor; FixedPoint.Unsigned paidToLiquidator; FixedPoint.Unsigned paidToDisputer; } // Liquidations are unique by ID per sponsor mapping(address => LiquidationData[]) public liquidations; // Total collateral in liquidation. FixedPoint.Unsigned public rawLiquidationCollateral; // Immutable contract parameters: // Amount of time for pending liquidation before expiry. // !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors. // Extremely low liveness values increase the chance that opportunistic invalid liquidations // expire without dispute, thereby decreasing the usability for sponsors and increasing the risk // for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic // token holder for the contract. uint256 public liquidationLiveness; // Required collateral:TRV ratio for a position to be considered sufficiently collateralized. FixedPoint.Unsigned public collateralRequirement; // Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer // Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%" FixedPoint.Unsigned public disputeBondPercentage; // Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public sponsorDisputeRewardPercentage; // Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute) // Represented as a multiplier, see above. FixedPoint.Unsigned public disputerDisputeRewardPercentage; /**************************************** * EVENTS * ****************************************/ event LiquidationCreated( address indexed sponsor, address indexed liquidator, uint256 indexed liquidationId, uint256 tokensOutstanding, uint256 lockedCollateral, uint256 liquidatedCollateral, uint256 liquidationTime ); event LiquidationDisputed( address indexed sponsor, address indexed liquidator, address indexed disputer, uint256 liquidationId, uint256 disputeBondAmount ); event DisputeSettled( address indexed caller, address indexed sponsor, address indexed liquidator, address disputer, uint256 liquidationId, bool disputeSucceeded ); event LiquidationWithdrawn( address indexed caller, uint256 paidToLiquidator, uint256 paidToDisputer, uint256 paidToSponsor, Status indexed liquidationStatus, uint256 settlementPrice ); /**************************************** * MODIFIERS * ****************************************/ modifier disputable(uint256 liquidationId, address sponsor) { _disputable(liquidationId, sponsor); _; } modifier withdrawable(uint256 liquidationId, address sponsor) { _withdrawable(liquidationId, sponsor); _; } /** * @notice Constructs the liquidatable contract. * @param params struct to define input parameters for construction of Liquidatable. Some params * are fed directly into the PricelessPositionManager's constructor within the inheritance tree. */ constructor(ConstructorParams memory params) public PricelessPositionManager( params.expirationTimestamp, params.withdrawalLiveness, params.collateralAddress, params.tokenAddress, params.finderAddress, params.priceFeedIdentifier, params.minSponsorTokens, params.timerAddress, params.financialProductLibraryAddress ) nonReentrant() { require(params.collateralRequirement.isGreaterThan(1)); require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1)); // Set liquidatable specific variables. liquidationLiveness = params.liquidationLiveness; collateralRequirement = params.collateralRequirement; disputeBondPercentage = params.disputeBondPercentage; sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage; disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage; } /**************************************** * LIQUIDATION FUNCTIONS * ****************************************/ /** * @notice Liquidates the sponsor's position if the caller has enough * synthetic tokens to retire the position's outstanding tokens. Liquidations above * a minimum size also reset an ongoing "slow withdrawal"'s liveness. * @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be * approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`. * @dev This contract must have the Burner role for the `tokenCurrency`. * @param sponsor address of the sponsor to liquidate. * @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. * @param deadline abort the liquidation if the transaction is mined after this timestamp. * @return liquidationId ID of the newly created liquidation. * @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position. * @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully. */ function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external fees() onlyPreExpiration() nonReentrant() returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ) { // Check that this transaction was mined pre-deadline. require(getCurrentTime() <= deadline, "Mined after deadline"); // Retrieve Position data for sponsor PositionData storage positionToLiquidate = _getPositionData(sponsor); tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding); require(tokensLiquidated.isGreaterThan(0)); // Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral, // then set this to 0, otherwise set it to (startCollateral - withdrawal request amount). FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral); FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0); if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) { startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount); } // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding; // The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken]. // maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal), "CR is more than max liq. price" ); // minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens. require( minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal), "CR is less than min liq. price" ); } // Compute final fee at time of liquidation. finalFeeBond = _computeFinalFees(); // These will be populated within the scope below. FixedPoint.Unsigned memory lockedCollateral; FixedPoint.Unsigned memory liquidatedCollateral; // Scoping to get rid of a stack too deep error. { FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding); // The actual amount of collateral that gets moved to the liquidation. lockedCollateral = startCollateral.mul(ratio); // For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of // withdrawal requests. liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio); // Part of the withdrawal request is also removed. Ideally: // liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral. FixedPoint.Unsigned memory withdrawalAmountToRemove = positionToLiquidate.withdrawalRequestAmount.mul(ratio); _reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove); } // Add to the global liquidation collateral count. _addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond)); // Construct liquidation object. // Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new // LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push. liquidationId = liquidations[sponsor].length; liquidations[sponsor].push( LiquidationData({ sponsor: sponsor, liquidator: msg.sender, state: Status.NotDisputed, liquidationTime: getCurrentTime(), tokensOutstanding: tokensLiquidated, lockedCollateral: lockedCollateral, liquidatedCollateral: liquidatedCollateral, rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)), disputer: address(0), settlementPrice: FixedPoint.fromUnscaledUint(0), finalFee: finalFeeBond }) ); // If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than // some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be // "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold // is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal. // We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter // denominated in token currency units and we can avoid adding another parameter. FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens; if ( positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal. positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired. tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold". ) { positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness); } emit LiquidationCreated( sponsor, msg.sender, liquidationId, tokensLiquidated.rawValue, lockedCollateral.rawValue, liquidatedCollateral.rawValue, getCurrentTime() ); // Destroy tokens tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue); tokenCurrency.burn(tokensLiquidated.rawValue); // Pull final fee from liquidator. collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue); } /** * @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond * and pay a fixed final fee charged on each price request. * @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes. * This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute * bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation. * @param liquidationId of the disputed liquidation. * @param sponsor the address of the sponsor whose liquidation is being disputed. * @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond). */ function dispute(uint256 liquidationId, address sponsor) external disputable(liquidationId, sponsor) fees() nonReentrant() returns (FixedPoint.Unsigned memory totalPaid) { LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId); // Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees. FixedPoint.Unsigned memory disputeBondAmount = disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul( _getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral) ); _addCollateral(rawLiquidationCollateral, disputeBondAmount); // Request a price from DVM. Liquidation is pending dispute until DVM returns a price. disputedLiquidation.state = Status.Disputed; disputedLiquidation.disputer = msg.sender; // Enqueue a request with the DVM. _requestOraclePriceLiquidation(disputedLiquidation.liquidationTime); emit LiquidationDisputed( sponsor, disputedLiquidation.liquidator, msg.sender, liquidationId, disputeBondAmount.rawValue ); totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee); // Pay the final fee for requesting price from the DVM. _payFinalFees(msg.sender, disputedLiquidation.finalFee); // Transfer the dispute bond amount from the caller to this contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue); } /** * @notice After a dispute has settled or after a non-disputed liquidation has expired, * anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer. * @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment. * If the dispute FAILED: only the liquidator can receive payment. * This method will revert if rewards have already been dispersed. * @param liquidationId uniquely identifies the sponsor's liquidation. * @param sponsor address of the sponsor associated with the liquidation. * @return data about rewards paid out. */ function withdrawLiquidation(uint256 liquidationId, address sponsor) public withdrawable(liquidationId, sponsor) fees() nonReentrant() returns (RewardsData memory) { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settles the liquidation if necessary. This call will revert if the price has not resolved yet. _settle(liquidationId, sponsor); // Calculate rewards as a function of the TRV. // Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata. FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral); FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice; FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation); FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation); FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue); FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage); FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation); // There are three main outcome states: either the dispute succeeded, failed or was not updated. // Based on the state, different parties of a liquidation receive different amounts. // After assigning rewards based on the liquidation status, decrease the total collateral held in this contract // by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes // precision loss. RewardsData memory rewards; if (liquidation.state == Status.DisputeSucceeded) { // If the dispute is successful then all three users should receive rewards: // Pay DISPUTER: disputer reward + dispute bond + returned final fee rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee); // Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue)); // Pay LIQUIDATOR: TRV - dispute reward - sponsor reward // If TRV > Collateral, then subtract rewards from collateral // NOTE: `payToLiquidator` should never be below zero since we enforce that // (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set. rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor); rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer); collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue); // In the case of a failed dispute only the liquidator can withdraw. } else if (liquidation.state == Status.DisputeFailed) { // Pay LIQUIDATOR: collateral + dispute bond + returned final fee rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); // If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this // state as a dispute failed and the liquidator can withdraw. } else if (liquidation.state == Status.NotDisputed) { // Pay LIQUIDATOR: collateral + returned final fee rewards.payToLiquidator = collateral.add(finalFee); // Transfer rewards and debit collateral rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator); collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue); } emit LiquidationWithdrawn( msg.sender, rewards.paidToLiquidator.rawValue, rewards.paidToDisputer.rawValue, rewards.paidToSponsor.rawValue, liquidation.state, settlementPrice.rawValue ); // Free up space after collateral is withdrawn by removing the liquidation object from the array. delete liquidations[sponsor][liquidationId]; return rewards; } /** * @notice Gets all liquidation information for a given sponsor address. * @param sponsor address of the position sponsor. * @return liquidationData array of all liquidation information for the given sponsor address. */ function getLiquidations(address sponsor) external view nonReentrantView() returns (LiquidationData[] memory liquidationData) { return liquidations[sponsor]; } /** * @notice Accessor method to calculate a transformed collateral requirement using the finanical product library specified during contract deployment. If no library was provided then no modification to the collateral requirement is done. * @param price input price used as an input to transform the collateral requirement. * @return transformedCollateralRequirement collateral requirement with transformation applied to it. * @dev This method should never revert. */ function transformCollateralRequirement(FixedPoint.Unsigned memory price) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _transformCollateralRequirement(price); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // This settles a liquidation if it is in the Disputed state. If not, it will immediately return. // If the liquidation is in the Disputed state, but a price is not available, this will revert. function _settle(uint256 liquidationId, address sponsor) internal { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); // Settlement only happens when state == Disputed and will only happen once per liquidation. // If this liquidation is not ready to be settled, this method should return immediately. if (liquidation.state != Status.Disputed) { return; } // Get the returned price from the oracle. If this has not yet resolved will revert. liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime); // Find the value of the tokens in the underlying collateral. FixedPoint.Unsigned memory tokenRedemptionValue = liquidation.tokensOutstanding.mul(liquidation.settlementPrice); // The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform // Collateral requirement method applies a from the financial Product library to change the scaled the collateral // requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change. FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice)); // If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid) // Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals. bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral); liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed; emit DisputeSettled( msg.sender, sponsor, liquidation.liquidator, liquidation.disputer, liquidationId, disputeSucceeded ); } function _pfc() internal view override returns (FixedPoint.Unsigned memory) { return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral)); } function _getLiquidationData(address sponsor, uint256 liquidationId) internal view returns (LiquidationData storage liquidation) { LiquidationData[] storage liquidationArray = liquidations[sponsor]; // Revert if the caller is attempting to access an invalid liquidation // (one that has never been created or one has never been initialized). require( liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized, "Invalid liquidation ID" ); return liquidationArray[liquidationId]; } function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) { return liquidation.liquidationTime.add(liquidationLiveness); } // These internal functions are supposed to act identically to modifiers, but re-used modifiers // unnecessarily increase contract bytecode size. // source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6 function _disputable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); require( (getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed), "Liquidation not disputable" ); } function _withdrawable(uint256 liquidationId, address sponsor) internal view { LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId); Status state = liquidation.state; // Must be disputed or the liquidation has passed expiry. require( (state > Status.NotDisputed) || ((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)), "Liquidation not withdrawable" ); } function _transformCollateralRequirement(FixedPoint.Unsigned memory price) internal view returns (FixedPoint.Unsigned memory) { if (!address(financialProductLibrary).isContract()) return collateralRequirement; try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns ( FixedPoint.Unsigned memory transformedCollateralRequirement ) { return transformedCollateralRequirement; } catch { return collateralRequirement; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Structured Note Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If * ETHUSD is above that strike, the contract pays out a given dollar amount of ETH. * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH * If ETHUSD < $400 at expiry, token is redeemed for 1 ETH. * If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM. */ contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable { mapping(address => FixedPoint.Unsigned) financialProductStrikes; /** * @notice Enables the deployer of the library to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the structured note to be applied to the financial product. * @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) financialProduct must exposes an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public onlyOwner nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the structured note payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThan(strike)) { return FixedPoint.fromUnscaledUint(1); } else { // Token expires to be worth strike $ worth of collateral. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH. return strike.div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price * of the structured note is greater than the strike then the collateral requirement scales down accordingly. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If the price is less than the strike than the original collateral requirement is used. if (oraclePrice.isLessThan(strike)) { return collateralRequirement; } else { // If the price is more than the strike then the collateral requirement is scaled by the strike. For example // a strike of $400 and a CR of 1.2 would yield: // ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2 // ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292 // ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96 return collateralRequirement.mul(strike.div(oraclePrice)); } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Pre-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made before expiration then a transformation is made to the identifier * & if it is at or after expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is before contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return financialProductTransformedIdentifiers[msg.sender]; } else { return identifier; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title Post-Expiration Identifier Transformation Financial Product Library * @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending * on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier * & if it is before expiration then the original identifier is returned. This library enables self referential * TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration. */ contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => bytes32) financialProductTransformedIdentifiers; /** * @notice Enables the deployer of the library to set the transformed identifier for an associated financial product. * @param financialProduct address of the financial product. * @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration. * @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A * transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct * must expose an expirationTimestamp method. */ function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier) public nonReentrant() { require(transformedIdentifier != "", "Cant set to empty transformation"); require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier; } /** * @notice Returns the transformed identifier associated with a given financial product address. * @param financialProduct address of the financial product. * @return transformed identifier for the associated financial product. */ function getTransformedIdentifierForFinancialProduct(address financialProduct) public view nonReentrantView() returns (bytes32) { return financialProductTransformedIdentifiers[financialProduct]; } /** * @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre. * @param identifier input price identifier to be transformed. * @param requestTime timestamp the identifier is to be used at. * @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it. */ function transformPriceIdentifier(bytes32 identifier, uint256 requestTime) public view override nonReentrantView() returns (bytes32) { require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation"); // If the request time is after contract expiration then return the transformed identifier. Else, return the // original price identifier. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return identifier; } else { return financialProductTransformedIdentifiers[msg.sender]; } } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title KPI Options Financial Product Library * @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract. * If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1. * Post-expiry, the collateral requirement is left as 1 and the price is left unchanged. */ contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable { /** * @notice Returns a transformed price for pre-expiry price requests. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with // each token backed 1:2 by collateral currency. Post-expiry, leave unchanged. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(2); } else { return oraclePrice; } } /** * @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled to a flat rate. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { // Always return 1. return FixedPoint.fromUnscaledUint(1); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./FinancialProductLibrary.sol"; import "../../../common/implementation/Lockable.sol"; /** * @title CoveredCall Financial Product Library * @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The * contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If * ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by * (oraclePrice - strikePrice) / oraclePrice; * Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH. * If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200). * If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400). * If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH. */ contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable { mapping(address => FixedPoint.Unsigned) private financialProductStrikes; /** * @notice Enables any address to set the strike price for an associated financial product. * @param financialProduct address of the financial product. * @param strikePrice the strike price for the covered call to be applied to the financial product. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) financialProduct must expose an expirationTimestamp method. */ function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice) public nonReentrant() { require(strikePrice.isGreaterThan(0), "Cant set 0 strike"); require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set"); require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract"); financialProductStrikes[financialProduct] = strikePrice; } /** * @notice Returns the strike price associated with a given financial product address. * @param financialProduct address of the financial product. * @return strikePrice for the associated financial product. */ function getStrikeForFinancialProduct(address financialProduct) public view nonReentrantView() returns (FixedPoint.Unsigned memory) { return financialProductStrikes[financialProduct]; } /** * @notice Returns a transformed price by applying the call option payout structure. * @param oraclePrice price from the oracle to be transformed. * @param requestTime timestamp the oraclePrice was requested at. * @return transformedPrice the input oracle price with the price transformation logic applied to it. */ function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with // each token backed 1:1 by collateral currency. if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) { return FixedPoint.fromUnscaledUint(1); } if (oraclePrice.isLessThanOrEqual(strike)) { return FixedPoint.fromUnscaledUint(0); } else { // Token expires to be worth the fraction of a collateral token that's in the money. // eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100). // Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always // true. return (oraclePrice.sub(strike)).div(oraclePrice); } } /** * @notice Returns a transformed collateral requirement by applying the covered call payout structure. * @param oraclePrice price from the oracle to transform the collateral requirement. * @param collateralRequirement financial products collateral requirement to be scaled according to price and strike. * @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it. */ function transformCollateralRequirement( FixedPoint.Unsigned memory oraclePrice, FixedPoint.Unsigned memory collateralRequirement ) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender]; require(strike.isGreaterThan(0), "Caller has no strike"); // Always return 1 because option must be collateralized by 1 token. return FixedPoint.fromUnscaledUint(1); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Lockable.sol"; import "./ReentrancyAttack.sol"; // Tests reentrancy guards defined in Lockable.sol. // Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol. contract ReentrancyMock is Lockable { uint256 public counter; constructor() public { counter = 0; } function callback() external nonReentrant { _count(); } function countAndSend(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("callback()")); attacker.callSender(func); } function countAndCall(ReentrancyAttack attacker) external nonReentrant { _count(); bytes4 func = bytes4(keccak256("getCount()")); attacker.callSender(func); } function countLocalRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); countLocalRecursive(n - 1); } } function countThisRecursive(uint256 n) public nonReentrant { if (n > 0) { _count(); // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1)); require(success, "ReentrancyMock: failed call"); } } function countLocalCall() public nonReentrant { getCount(); } function countThisCall() public nonReentrant { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = address(this).call(abi.encodeWithSignature("getCount()")); require(success, "ReentrancyMock: failed call"); } function getCount() public view nonReentrantView returns (uint256) { return counter; } function _count() private { counter += 1; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; // Tests reentrancy guards defined in Lockable.sol. // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol. contract ReentrancyAttack { function callSender(bytes4 data) public { // solhint-disable-next-line avoid-low-level-calls (bool success, ) = msg.sender.call(abi.encodeWithSelector(data)); require(success, "ReentrancyAttack: failed call"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/FeePayer.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../oracle/implementation/ContractCreator.sol"; /** * @title Token Deposit Box * @notice This is a minimal example of a financial template that depends on price requests from the DVM. * This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral. * The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount. * When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM. * For simplicty, the user is constrained to have one outstanding withdrawal request at any given time. * Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box, * and final fees are charged on each price request. * * This example is intended to accompany a technical tutorial for how to integrate the DVM into a project. * The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price * requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework. * * The typical user flow would be: * - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit * box is therefore wETH. * The user can subsequently make withdrawal requests for USD-denominated amounts of wETH. * - User deposits 10 wETH into their deposit box. * - User later requests to withdraw $100 USD of wETH. * - DepositBox asks DVM for latest wETH/USD exchange rate. * - DVM resolves the exchange rate at: 1 wETH is worth 200 USD. * - DepositBox transfers 0.5 wETH to user. */ contract DepositBox is FeePayer, ContractCreator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; // Represents a single caller's deposit box. All collateral is held by this contract. struct DepositBoxData { // Requested amount of collateral, denominated in quote asset of the price identifier. // Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then // this represents a withdrawal request for 100 USD worth of wETH. FixedPoint.Unsigned withdrawalRequestAmount; // Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`. uint256 requestPassTimestamp; // Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral(). // To add or remove collateral, use _addCollateral() and _removeCollateral(). FixedPoint.Unsigned rawCollateral; } // Maps addresses to their deposit boxes. Each address can have only one position. mapping(address => DepositBoxData) private depositBoxes; // Unique identifier for DVM price feed ticker. bytes32 private priceIdentifier; // Similar to the rawCollateral in DepositBoxData, this value should not be used directly. // _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust. FixedPoint.Unsigned private rawTotalDepositBoxCollateral; // This blocks every public state-modifying method until it flips to true, via the `initialize()` method. bool private initialized; /**************************************** * EVENTS * ****************************************/ event NewDepositBox(address indexed user); event EndedDepositBox(address indexed user); event Deposit(address indexed user, uint256 indexed collateralAmount); event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp); event RequestWithdrawalExecuted( address indexed user, uint256 indexed collateralAmount, uint256 exchangeRate, uint256 requestPassTimestamp ); event RequestWithdrawalCanceled( address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp ); /**************************************** * MODIFIERS * ****************************************/ modifier noPendingWithdrawal(address user) { _depositBoxHasNoPendingWithdrawal(user); _; } modifier isInitialized() { _isInitialized(); _; } /**************************************** * PUBLIC FUNCTIONS * ****************************************/ /** * @notice Construct the DepositBox. * @param _collateralAddress ERC20 token to be deposited. * @param _finderAddress UMA protocol Finder used to discover other protocol contracts. * @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited. * The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20 * currency deposited into this account, and it is denominated in the "quote" asset on withdrawals. * An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor( address _collateralAddress, address _finderAddress, bytes32 _priceIdentifier, address _timerAddress ) public ContractCreator(_finderAddress) FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() { require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier"); priceIdentifier = _priceIdentifier; } /** * @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required * to make price requests in production environments. * @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM. * Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role * in order to register with the `Registry`. But, its address is not known until after deployment. */ function initialize() public nonReentrant() { initialized = true; _registerContract(new address[](0), address(this)); } /** * @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box. * @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`. * @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position. */ function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() { require(collateralAmount.isGreaterThan(0), "Invalid collateral amount"); DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) { emit NewDepositBox(msg.sender); } // Increase the individual deposit box and global collateral balance by collateral amount. _incrementCollateralBalances(depositBoxData, collateralAmount); emit Deposit(msg.sender, collateralAmount.rawValue); // Move collateral currency from sender to contract. collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue); } /** * @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount` * from their position denominated in the quote asset of the price identifier, following a DVM price resolution. * @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time. * Only one withdrawal request can exist for the user. * @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw. */ function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount) public isInitialized() noPendingWithdrawal(msg.sender) nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount"); // Update the position object for the user. depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount; depositBoxData.requestPassTimestamp = getCurrentTime(); emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp); // Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee. FixedPoint.Unsigned memory finalFee = _computeFinalFees(); require( _getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee), "Cannot pay final fee" ); _payFinalFees(address(this), finalFee); // A price request is sent for the current timestamp. _requestOraclePrice(depositBoxData.requestPassTimestamp); } /** * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), * withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. * @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested * amount exceeds the collateral in the position (due to paying fees). * @return amountWithdrawn The actual amount of collateral withdrawn. */ function executeWithdrawal() external isInitialized() fees() nonReentrant() returns (FixedPoint.Unsigned memory amountWithdrawn) { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require( depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(), "Invalid withdraw request" ); // Get the resolved price or revert. FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp); // Calculate denomated amount of collateral based on resolved exchange rate. // Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. // Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. FixedPoint.Unsigned memory denominatedAmountToWithdraw = depositBoxData.withdrawalRequestAmount.div(exchangeRate); // If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) { denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral); // Reset the position state as all the value has been removed after settlement. emit EndedDepositBox(msg.sender); } // Decrease the individual deposit box and global collateral balance. amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw); emit RequestWithdrawalExecuted( msg.sender, amountWithdrawn.rawValue, exchangeRate.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); // Transfer approved withdrawal amount from the contract to the caller. collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue); } /** * @notice Cancels a pending withdrawal request. */ function cancelWithdrawal() external isInitialized() nonReentrant() { DepositBoxData storage depositBoxData = depositBoxes[msg.sender]; require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal"); emit RequestWithdrawalCanceled( msg.sender, depositBoxData.withdrawalRequestAmount.rawValue, depositBoxData.requestPassTimestamp ); // Reset withdrawal request by setting withdrawal request timestamp to 0. _resetWithdrawalRequest(depositBoxData); } /** * @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but * because this is a minimal demo they will simply exit silently. */ function emergencyShutdown() external override isInitialized() nonReentrant() { return; } /** * @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently. */ function remargin() external override isInitialized() nonReentrant() { return; } /** * @notice Accessor method for a user's collateral. * @dev This is necessary because the struct returned by the depositBoxes() method shows * rawCollateral, which isn't a user-readable value. * @param user address whose collateral amount is retrieved. * @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal). */ function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral); } /** * @notice Accessor method for the total collateral stored within the entire contract. * @return the total fee-adjusted collateral amount in the contract (i.e. across all users). */ function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ // Requests a price for `priceIdentifier` at `requestedTime` from the Oracle. function _requestOraclePrice(uint256 requestedTime) internal { OracleInterface oracle = _getOracle(); oracle.requestPrice(priceIdentifier, requestedTime); } // Ensure individual and global consistency when increasing collateral balances. Returns the change to the position. function _incrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _addCollateral(depositBoxData.rawCollateral, collateralAmount); return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount); } // Ensure individual and global consistency when decrementing collateral balances. Returns the change to the // position. We elect to return the amount that the global collateral is decreased by, rather than the individual // position's collateral, because we need to maintain the invariant that the global collateral is always // <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn. function _decrementCollateralBalances( DepositBoxData storage depositBoxData, FixedPoint.Unsigned memory collateralAmount ) internal returns (FixedPoint.Unsigned memory) { _removeCollateral(depositBoxData.rawCollateral, collateralAmount); return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount); } function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal { depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0); depositBoxData.requestPassTimestamp = 0; } function _depositBoxHasNoPendingWithdrawal(address user) internal view { require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal"); } function _isInitialized() internal view { require(initialized, "Uninitialized contract"); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getOracle() internal view returns (OracleInterface) { return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle)); } // Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request. function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) { OracleInterface oracle = _getOracle(); require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price"); int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime); // For simplicity we don't want to deal with negative prices. if (oraclePrice < 0) { oraclePrice = 0; } return FixedPoint.Unsigned(uint256(oraclePrice)); } // `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from // which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the // contract. function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) { return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "./VotingToken.sol"; /** * @title Migration contract for VotingTokens. * @dev Handles migrating token holders from one token to the next. */ contract TokenMigrator { using FixedPoint for FixedPoint.Unsigned; /**************************************** * INTERNAL VARIABLES AND STORAGE * ****************************************/ VotingToken public oldToken; ExpandedIERC20 public newToken; uint256 public snapshotId; FixedPoint.Unsigned public rate; mapping(address => bool) public hasMigrated; /** * @notice Construct the TokenMigrator contract. * @dev This function triggers the snapshot upon which all migrations will be based. * @param _rate the number of old tokens it takes to generate one new token. * @param _oldToken address of the token being migrated from. * @param _newToken address of the token being migrated to. */ constructor( FixedPoint.Unsigned memory _rate, address _oldToken, address _newToken ) public { // Prevents division by 0 in migrateTokens(). // Also it doesn’t make sense to have “0 old tokens equate to 1 new token”. require(_rate.isGreaterThan(0), "Rate can't be 0"); rate = _rate; newToken = ExpandedIERC20(_newToken); oldToken = VotingToken(_oldToken); snapshotId = oldToken.snapshot(); } /** * @notice Migrates the tokenHolder's old tokens to new tokens. * @dev This function can only be called once per `tokenHolder`. Anyone can call this method * on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier. * @param tokenHolder address of the token holder to migrate. */ function migrateTokens(address tokenHolder) external { require(!hasMigrated[tokenHolder], "Already migrated tokens"); hasMigrated[tokenHolder] = true; FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId)); if (!oldBalance.isGreaterThan(0)) { return; } FixedPoint.Unsigned memory newBalance = oldBalance.div(rate); require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed"); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/ExpandedERC20.sol"; contract TokenSender { function transferERC20( address tokenAddress, address recipientAddress, uint256 amount ) public returns (bool) { IERC20 token = IERC20(tokenAddress); token.transfer(recipientAddress, amount); return true; } } pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IDepositExecute.sol"; import "./IBridge.sol"; import "./IERCHandler.sol"; import "./IGenericHandler.sol"; /** @title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions. @author ChainSafe Systems. */ contract Bridge is Pausable, AccessControl { using SafeMath for uint256; uint8 public _chainID; uint256 public _relayerThreshold; uint256 public _totalRelayers; uint256 public _totalProposals; uint256 public _fee; uint256 public _expiry; enum Vote { No, Yes } enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled } struct Proposal { bytes32 _resourceID; bytes32 _dataHash; address[] _yesVotes; address[] _noVotes; ProposalStatus _status; uint256 _proposedBlock; } // destinationChainID => number of deposits mapping(uint8 => uint64) public _depositCounts; // resourceID => handler address mapping(bytes32 => address) public _resourceIDToHandlerAddress; // depositNonce => destinationChainID => bytes mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords; // destinationChainID + depositNonce => dataHash => Proposal mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals; // destinationChainID + depositNonce => dataHash => relayerAddress => bool mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal; event RelayerThresholdChanged(uint256 indexed newThreshold); event RelayerAdded(address indexed relayer); event RelayerRemoved(address indexed relayer); event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce); event ProposalEvent( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID, bytes32 dataHash ); event ProposalVote( uint8 indexed originChainID, uint64 indexed depositNonce, ProposalStatus indexed status, bytes32 resourceID ); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); modifier onlyAdmin() { _onlyAdmin(); _; } modifier onlyAdminOrRelayer() { _onlyAdminOrRelayer(); _; } modifier onlyRelayers() { _onlyRelayers(); _; } function _onlyAdminOrRelayer() private { require( hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender), "sender is not relayer or admin" ); } function _onlyAdmin() private { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role"); } function _onlyRelayers() private { require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role"); } /** @notice Initializes Bridge, creates and grants {msg.sender} the admin role, creates and grants {initialRelayers} the relayer role. @param chainID ID of chain the Bridge contract exists on. @param initialRelayers Addresses that should be initially granted the relayer role. @param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed. */ constructor( uint8 chainID, address[] memory initialRelayers, uint256 initialRelayerThreshold, uint256 fee, uint256 expiry ) public { _chainID = chainID; _relayerThreshold = initialRelayerThreshold; _fee = fee; _expiry = expiry; _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE); for (uint256 i; i < initialRelayers.length; i++) { grantRole(RELAYER_ROLE, initialRelayers[i]); _totalRelayers++; } } /** @notice Returns true if {relayer} has the relayer role. @param relayer Address to check. */ function isRelayer(address relayer) external view returns (bool) { return hasRole(RELAYER_ROLE, relayer); } /** @notice Removes admin role from {msg.sender} and grants it to {newAdmin}. @notice Only callable by an address that currently has the admin role. @param newAdmin Address that admin role will be granted to. */ function renounceAdmin(address newAdmin) external onlyAdmin { grantRole(DEFAULT_ADMIN_ROLE, newAdmin); renounceRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** @notice Pauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminPauseTransfers() external onlyAdmin { _pause(); } /** @notice Unpauses deposits, proposal creation and voting, and deposit executions. @notice Only callable by an address that currently has the admin role. */ function adminUnpauseTransfers() external onlyAdmin { _unpause(); } /** @notice Modifies the number of votes required for a proposal to be considered passed. @notice Only callable by an address that currently has the admin role. @param newThreshold Value {_relayerThreshold} will be changed to. @notice Emits {RelayerThresholdChanged} event. */ function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin { _relayerThreshold = newThreshold; emit RelayerThresholdChanged(newThreshold); } /** @notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be added. @notice Emits {RelayerAdded} event. */ function adminAddRelayer(address relayerAddress) external onlyAdmin { require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!"); grantRole(RELAYER_ROLE, relayerAddress); emit RelayerAdded(relayerAddress); _totalRelayers++; } /** @notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count. @notice Only callable by an address that currently has the admin role. @param relayerAddress Address of relayer to be removed. @notice Emits {RelayerRemoved} event. */ function adminRemoveRelayer(address relayerAddress) external onlyAdmin { require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!"); revokeRole(RELAYER_ROLE, relayerAddress); emit RelayerRemoved(relayerAddress); _totalRelayers--; } /** @notice Sets a new resource for handler contracts that use the IERCHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetResource( address handlerAddress, bytes32 resourceID, address tokenAddress ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IERCHandler handler = IERCHandler(handlerAddress); handler.setResource(resourceID, tokenAddress); } /** @notice Sets a new resource for handler contracts that use the IGenericHandler interface, and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetGenericResource( address handlerAddress, bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external onlyAdmin { _resourceIDToHandlerAddress[resourceID] = handlerAddress; IGenericHandler handler = IGenericHandler(handlerAddress); handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice Sets a resource as burnable for handler contracts that use the IERCHandler interface. @notice Only callable by an address that currently has the admin role. @param handlerAddress Address of handler resource will be set for. @param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.setBurnable(tokenAddress); } /** @notice Returns a proposal. @param originChainID Chain ID deposit originated from. @param depositNonce ID of proposal generated by proposal's origin Bridge contract. @param dataHash Hash of data to be provided when deposit proposal is executed. @return Proposal which consists of: - _dataHash Hash of data to be provided when deposit proposal is executed. - _yesVotes Number of votes in favor of proposal. - _noVotes Number of votes against proposal. - _status Current status of proposal. */ function getProposal( uint8 originChainID, uint64 depositNonce, bytes32 dataHash ) external view returns (Proposal memory) { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID); return _proposals[nonceAndID][dataHash]; } /** @notice Changes deposit fee. @notice Only callable by admin. @param newFee Value {_fee} will be updated to. */ function adminChangeFee(uint256 newFee) external onlyAdmin { require(_fee != newFee, "Current fee is equal to new fee"); _fee = newFee; } /** @notice Used to manually withdraw funds from ERC safes. @param handlerAddress Address of handler to withdraw from. @param tokenAddress Address of token to withdraw. @param recipient Address to withdraw tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw. */ function adminWithdraw( address handlerAddress, address tokenAddress, address recipient, uint256 amountOrTokenID ) external onlyAdmin { IERCHandler handler = IERCHandler(handlerAddress); handler.withdraw(tokenAddress, recipient, amountOrTokenID); } /** @notice Initiates a transfer using a specified handler contract. @notice Only callable when Bridge is not paused. @param destinationChainID ID of chain deposit will be bridged to. @param resourceID ResourceID used to find address of handler to be used for deposit. @param data Additional data to be passed to specified handler. @notice Emits {Deposit} event. */ function deposit( uint8 destinationChainID, bytes32 resourceID, bytes calldata data ) external payable whenNotPaused { require(msg.value == _fee, "Incorrect fee supplied"); address handler = _resourceIDToHandlerAddress[resourceID]; require(handler != address(0), "resourceID not mapped to handler"); uint64 depositNonce = ++_depositCounts[destinationChainID]; _depositRecords[depositNonce][destinationChainID] = data; IDepositExecute depositHandler = IDepositExecute(handler); depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data); emit Deposit(destinationChainID, resourceID, depositNonce); } /** @notice When called, {msg.sender} will be marked as voting in favor of proposal. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data provided when deposit was made. @notice Proposal must not have already been passed or executed. @notice {msg.sender} must not have already voted on proposal. @notice Emits {ProposalEvent} event with status indicating the proposal status. @notice Emits {ProposalVote} event. */ function voteProposal( uint8 chainID, uint64 depositNonce, bytes32 resourceID, bytes32 dataHash ) external onlyRelayers whenNotPaused { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID"); require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled"); require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted"); if (uint256(proposal._status) == 0) { ++_totalProposals; _proposals[nonceAndID][dataHash] = Proposal({ _resourceID: resourceID, _dataHash: dataHash, _yesVotes: new address[](1), _noVotes: new address[](0), _status: ProposalStatus.Active, _proposedBlock: block.number }); proposal._yesVotes[0] = msg.sender; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash); } else { if (block.number.sub(proposal._proposedBlock) > _expiry) { // if the number of blocks that has passed since this proposal was // submitted exceeds the expiry threshold set, cancel the proposal proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash); } else { require(dataHash == proposal._dataHash, "datahash mismatch"); proposal._yesVotes.push(msg.sender); } } if (proposal._status != ProposalStatus.Cancelled) { _hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true; emit ProposalVote(chainID, depositNonce, proposal._status, resourceID); // If _depositThreshold is set to 1, then auto finalize // or if _relayerThreshold has been exceeded if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) { proposal._status = ProposalStatus.Passed; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash); } } } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param depositNonce ID of deposited generated by origin Bridge contract. @param dataHash Hash of data originally provided when deposit was made. @notice Proposal must be past expiry threshold. @notice Emits {ProposalEvent} event with status {Cancelled}. */ function cancelProposal( uint8 chainID, uint64 depositNonce, bytes32 dataHash ) public onlyAdminOrRelayer { uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled"); require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold"); proposal._status = ProposalStatus.Cancelled; emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash); } /** @notice Executes a deposit proposal that is considered passed using a specified handler contract. @notice Only callable by relayers when Bridge is not paused. @param chainID ID of chain deposit originated from. @param resourceID ResourceID to be used when making deposits. @param depositNonce ID of deposited generated by origin Bridge contract. @param data Data originally provided when deposit was made. @notice Proposal must have Passed status. @notice Hash of {data} must equal proposal's {dataHash}. @notice Emits {ProposalEvent} event with status {Executed}. */ function executeProposal( uint8 chainID, uint64 depositNonce, bytes calldata data, bytes32 resourceID ) external onlyRelayers whenNotPaused { address handler = _resourceIDToHandlerAddress[resourceID]; uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID); bytes32 dataHash = keccak256(abi.encodePacked(handler, data)); Proposal storage proposal = _proposals[nonceAndID][dataHash]; require(proposal._status != ProposalStatus.Inactive, "proposal is not active"); require(proposal._status == ProposalStatus.Passed, "proposal already transferred"); require(dataHash == proposal._dataHash, "data doesn't match datahash"); proposal._status = ProposalStatus.Executed; IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]); depositHandler.executeProposal(proposal._resourceID, data); emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash); } /** @notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1. This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0. @param addrs Array of addresses to transfer {amounts} to. @param amounts Array of amonuts to transfer to {addrs}. */ function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin { for (uint256 i = 0; i < addrs.length; i++) { addrs[i].transfer(amounts[i]); } } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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, _msgSender())); * ... * } * ``` * * 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}. */ 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 `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. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _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()); } } } pragma solidity ^0.6.0; /** @title Interface for handler contracts that support deposits and deposit executions. @author ChainSafe Systems. */ interface IDepositExecute { /** @notice It is intended that deposit are made using the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of additional data needed for a specific deposit. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external; /** @notice It is intended that proposals are executed by the Bridge contract. @param data Consists of additional data needed for a specific deposit execution. */ function executeProposal(bytes32 resourceID, bytes calldata data) external; } pragma solidity ^0.6.0; /** @title Interface for Bridge contract. @author ChainSafe Systems. */ interface IBridge { /** @notice Exposing getter for {_chainID} instead of forcing the use of call. @return uint8 The {_chainID} that is currently set for the Bridge contract. */ function _chainID() external returns (uint8); } pragma solidity ^0.6.0; /** @title Interface to be used with handlers that support ERC20s and ERC721s. @author ChainSafe Systems. */ interface IERCHandler { /** @notice Correlates {resourceID} with {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. */ function setResource(bytes32 resourceID, address contractAddress) external; /** @notice Marks {contractAddress} as mintable/burnable. @param contractAddress Address of contract to be used when making or executing deposits. */ function setBurnable(address contractAddress) external; /** @notice Used to manually release funds from ERC safes. @param tokenAddress Address of token contract to release. @param recipient Address to release tokens to. @param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release. */ function withdraw( address tokenAddress, address recipient, uint256 amountOrTokenID ) external; } pragma solidity ^0.6.0; /** @title Interface for handler that handles generic deposits and deposit executions. @author ChainSafe Systems. */ interface IGenericHandler { /** @notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external; } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IGenericHandler.sol"; /** @title Handles generic deposits and deposit executions. @author ChainSafe Systems. @notice This contract is intended to be used with the Bridge contract. */ contract GenericHandler is IGenericHandler { address public _bridgeAddress; struct DepositRecord { uint8 _destinationChainID; address _depositer; bytes32 _resourceID; bytes _metaData; } // depositNonce => Deposit Record mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords; // resourceID => contract address mapping(bytes32 => address) public _resourceIDToContractAddress; // contract address => resourceID mapping(address => bytes32) public _contractAddressToResourceID; // contract address => deposit function signature mapping(address => bytes4) public _contractAddressToDepositFunctionSignature; // contract address => execute proposal function signature mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature; // token contract address => is whitelisted mapping(address => bool) public _contractWhitelist; modifier onlyBridge() { _onlyBridge(); _; } function _onlyBridge() private { require(msg.sender == _bridgeAddress, "sender must be bridge contract"); } /** @param bridgeAddress Contract address of previously deployed Bridge. @param initialResourceIDs Resource IDs used to identify a specific contract address. These are the Resource IDs this contract will initially support. @param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be called to perform deposit and execution calls. @param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {deposit} @param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to, and are the function that will be called when executing {executeProposal} @dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures}, and {initialExecuteFunctionSignatures} must all have the same length. Also, values must be ordered in the way that that index x of any mentioned array must be intended for value x of any other array, e.g. {initialContractAddresses}[0] is the intended address for {initialDepositFunctionSignatures}[0]. */ constructor( address bridgeAddress, bytes32[] memory initialResourceIDs, address[] memory initialContractAddresses, bytes4[] memory initialDepositFunctionSignatures, bytes4[] memory initialExecuteFunctionSignatures ) public { require( initialResourceIDs.length == initialContractAddresses.length, "initialResourceIDs and initialContractAddresses len mismatch" ); require( initialContractAddresses.length == initialDepositFunctionSignatures.length, "provided contract addresses and function signatures len mismatch" ); require( initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length, "provided deposit and execute function signatures len mismatch" ); _bridgeAddress = bridgeAddress; for (uint256 i = 0; i < initialResourceIDs.length; i++) { _setResource( initialResourceIDs[i], initialContractAddresses[i], initialDepositFunctionSignatures[i], initialExecuteFunctionSignatures[i] ); } } /** @param depositNonce This ID will have been generated by the Bridge contract. @param destId ID of chain deposit will be bridged to. @return DepositRecord which consists of: - _destinationChainID ChainID deposited tokens are intended to end up on. - _resourceID ResourceID used when {deposit} was executed. - _depositer Address that initially called {deposit} in the Bridge contract. - _metaData Data to be passed to method executed in corresponding {resourceID} contract. */ function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) { return _depositRecords[destId][depositNonce]; } /** @notice First verifies {_resourceIDToContractAddress}[{resourceID}] and {_contractAddressToResourceID}[{contractAddress}] are not already set, then sets {_resourceIDToContractAddress} with {contractAddress}, {_contractAddressToResourceID} with {resourceID}, {_contractAddressToDepositFunctionSignature} with {depositFunctionSig}, {_contractAddressToExecuteFunctionSignature} with {executeFunctionSig}, and {_contractWhitelist} to true for {contractAddress}. @param resourceID ResourceID to be used when making deposits. @param contractAddress Address of contract to be called when a deposit is made and a deposited is executed. @param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made. @param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed. */ function setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) external override onlyBridge { _setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig); } /** @notice A deposit is initiatied by making a deposit in the Bridge contract. @param destinationChainID Chain ID deposit is expected to be bridged to. @param depositNonce This value is generated as an ID by the Bridge contract. @param depositer Address of account making the deposit in the Bridge contract. @param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 64 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function deposit( bytes32 resourceID, uint8 destinationChainID, uint64 depositNonce, address depositer, bytes calldata data ) external onlyBridge { bytes32 lenMetadata; bytes memory metadata; assembly { // Load length of metadata from data + 64 lenMetadata := calldataload(0xC4) // Load free memory pointer metadata := mload(0x40) mstore(0x40, add(0x20, add(metadata, lenMetadata))) // func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) + // bytes length (32) + resourceId (32) + length (32) = 0xC4 calldatacopy( metadata, // copy to metadata 0xC4, // copy from calldata after metadata length declaration @0xC4 sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up)) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metadata); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } _depositRecords[destinationChainID][depositNonce] = DepositRecord( destinationChainID, depositer, resourceID, metadata ); } /** @notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract. @param data Consists of {resourceID}, {lenMetaData}, and {metaData}. @notice Data passed into the function should be constructed as follows: len(data) uint256 bytes 0 - 32 data bytes bytes 32 - END @notice {contractAddress} is required to be whitelisted @notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set, {metaData} is expected to consist of needed function arguments. */ function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge { bytes memory metaData; assembly { // metadata has variable length // load free memory pointer to store metadata metaData := mload(0x40) // first 32 bytes of variable length in storage refer to length let lenMeta := calldataload(0x64) mstore(0x40, add(0x60, add(metaData, lenMeta))) // in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params calldatacopy( metaData, // copy to metaData 0x64, // copy from calldata after data length declaration at 0x64 sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64) ) } address contractAddress = _resourceIDToContractAddress[resourceID]; require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted"); bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress]; if (sig != bytes4(0)) { bytes memory callData = abi.encodePacked(sig, metaData); (bool success, ) = contractAddress.call(callData); require(success, "delegatecall to contractAddress failed"); } } function _setResource( bytes32 resourceID, address contractAddress, bytes4 depositFunctionSig, bytes4 executeFunctionSig ) internal { _resourceIDToContractAddress[resourceID] = contractAddress; _contractAddressToResourceID[contractAddress] = resourceID; _contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig; _contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig; _contractWhitelist[contractAddress] = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../../interfaces/VotingInterface.sol"; import "../VoteTiming.sol"; // Wraps the library VoteTiming for testing purposes. contract VoteTimingTest { using VoteTiming for VoteTiming.Data; VoteTiming.Data public voteTiming; constructor(uint256 phaseLength) public { wrapInit(phaseLength); } function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) { return voteTiming.computeCurrentRoundId(currentTime); } function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) { return voteTiming.computeCurrentPhase(currentTime); } function wrapInit(uint256 phaseLength) public { voteTiming.init(phaseLength); } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "@uniswap/lib/contracts/libraries/Babylonian.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/lib/contracts/libraries/FullMath.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; /** * @title UniswapBroker * @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual * synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically * swap and move a uniswap market. */ contract UniswapBroker { using SafeMath for uint256; /** * @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as * possible to the truePrice. * @dev True price is expressed in the ratio of token A to token B. * @dev The caller must approve this contract to spend whichever token is intended to be swapped. * @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param uniswapFactory address of the uniswap factory used to fetch current pair reserves. * @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure * out which tokens need to be exchanged to move the market to the desired "true" price. * @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price * and the 1st value is the the denominator of the true price. * @param maxSpendTokens array of unit to represent the max to spend in the two tokens. * @param to recipient of the trade proceeds. * @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert. */ function swapToPrice( bool tradingAsEOA, address uniswapRouter, address uniswapFactory, address[2] memory swappedTokens, uint256[2] memory truePriceTokens, uint256[2] memory maxSpendTokens, address to, uint256 deadline ) public { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); // true price is expressed as a ratio, so both values must be non-zero require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE"); // caller can specify 0 for either if they wish to swap in only one direction, but not both require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND"); bool aToB; uint256 amountIn; { (uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]); (aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB); } require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN"); // spend up to the allowance of the token in uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1]; if (amountIn > maxSpend) { amountIn = maxSpend; } address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1]; address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0]; TransferHelper.safeApprove(tokenIn, address(router), amountIn); if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address[] memory path = new address[](2); path[0] = tokenIn; path[1] = tokenOut; router.swapExactTokensForTokens( amountIn, 0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests. path, to, deadline ); } /** * @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the * uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move * the pool price to be equal to the true price. * @dev Note that this method uses the Babylonian square root method which has a small margin of error which will * result in a small over or under estimation on the size of the trade needed. * @param truePriceTokenA the nominator of the true price. * @param truePriceTokenB the denominator of the true price. * @param reserveA number of token A in the pair reserves * @param reserveB number of token B in the pair reserves */ // function computeTradeToMoveMarket( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) public pure returns (bool aToB, uint256 amountIn) { aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA.mul(reserveB); // The trade ∆a of token a required to move the market to some desired price P' from the current price P can be // found with ∆a=(kP')^1/2-Ra. uint256 leftSide = Babylonian.sqrt( FullMath.mulDiv( invariant, aToB ? truePriceTokenA : truePriceTokenB, aToB ? truePriceTokenB : truePriceTokenA ) ); uint256 rightSide = (aToB ? reserveA : reserveB); if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price back to the true price. amountIn = leftSide.sub(rightSide); } // The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol // We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound // to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so // unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant // handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker // are simply moved here to maintain truffle support. function getReserves( address factory, address tokenA, address tokenB ) public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } 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"); } // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address tokenA, address tokenB ) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ); } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; // this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2); // however that code costs significantly more gas uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // SPDX-License-Identifier: CC-BY-4.0 pragma solidity >=0.4.0; // taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // license is CC-BY-4.0 library FullMath { function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; if (h == 0) return l / d; require(h < d, 'FullMath: FULLDIV_OVERFLOW'); return fullDiv(l, h, d); } } 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.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol"; import "../../common/implementation/FixedPoint.sol"; /** * @title ReserveCurrencyLiquidator * @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of * financial contracts. Is assumed to be called by a DSProxy which holds reserve currency. */ contract ReserveCurrencyLiquidator { using SafeMath for uint256; using FixedPoint for FixedPoint.Unsigned; /** * @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to * liquidate a position within one transaction. * @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending * liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has * passed liveness. At this point the position can be manually unwound. * @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted. * These existing tokens will be used first before any swaps or mints are done. * @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough * collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves. * @param uniswapRouter address of the uniswap router used to facilitate trades. * @param financialContract address of the financial contract on which the liquidation is occurring. * @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy. * @param liquidatedSponsor address of the sponsor to be liquidated. * @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage. * @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value. * @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value. * @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt. * @param deadline abort the trade and liquidation if the transaction is mined after this timestamp. **/ function swapMintLiquidate( address uniswapRouter, address financialContract, address reserveCurrency, address liquidatedSponsor, FixedPoint.Unsigned calldata maxReserveTokenSpent, FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) public { IFinancialContract fc = IFinancialContract(financialContract); // 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already // has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall). FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc)); // 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics. FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding()); FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr); // 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any // collateral needed to mint the token short fall. FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall); // 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this // will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0. FixedPoint.Unsigned memory collateralToBePurchased = subOrZero(totalCollateralRequired, getCollateralBalance(fc)); // 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall. // Note the path assumes a direct route from the reserve currency to the collateral currency. if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) { IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter); address[] memory path = new address[](2); path[0] = reserveCurrency; path[1] = fc.collateralCurrency(); TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue); router.swapTokensForExactTokens( collateralToBePurchased.rawValue, maxReserveTokenSpent.rawValue, path, address(this), deadline ); } // 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve // or not enough collateral in the contract) the script should try to liquidate as much as it can regardless. // Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall // as the maximum tokens that could be liquidated at the current GCR. if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) { totalCollateralRequired = getCollateralBalance(fc); collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc)); tokenShortfall = collateralToMintShortfall.divCeil(gcr); } // 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR. // If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral // currency as this is needed to pay the final fee in the liquidation tx. TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue); if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall); // The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full // token token balance at this point if there was a shortfall. FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate; if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc); // 6. Liquidate position with newly minted synthetics. TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue); fc.createLiquidation( liquidatedSponsor, minCollateralPerTokenLiquidated, maxCollateralPerTokenLiquidated, liquidatableTokens, deadline ); } // Helper method to work around subtraction overflow in the case of: a - b with b > a. function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b) internal pure returns (FixedPoint.Unsigned memory) { return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b); } // Helper method to return the current final fee for a given financial contract instance. function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency()); } // Helper method to return the collateral balance of this contract. function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this))); } // Helper method to return the synthetic balance of this contract. function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) { return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this))); } } // Define some simple interfaces for dealing with UMA contracts. interface IFinancialContract { struct PositionData { FixedPoint.Unsigned tokensOutstanding; uint256 withdrawalRequestPassTimestamp; FixedPoint.Unsigned withdrawalRequestAmount; FixedPoint.Unsigned rawCollateral; uint256 transferPositionRequestPassTimestamp; } function positions(address sponsor) external returns (PositionData memory); function collateralCurrency() external returns (address); function tokenCurrency() external returns (address); function finder() external returns (address); function pfc() external returns (FixedPoint.Unsigned memory); function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory); function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external; function createLiquidation( address sponsor, FixedPoint.Unsigned calldata minCollateralPerToken, FixedPoint.Unsigned calldata maxCollateralPerToken, FixedPoint.Unsigned calldata maxTokensToLiquidate, uint256 deadline ) external returns ( uint256 liquidationId, FixedPoint.Unsigned memory tokensLiquidated, FixedPoint.Unsigned memory finalFeeBond ); } interface IStore { function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory); } interface IFinder { function getImplementationAddress(bytes32 interfaceName) external view returns (address); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; // Simple contract used to redeem tokens using a DSProxy from an emp. contract TokenRedeemer { function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens) public returns (FixedPoint.Unsigned memory) { IFinancialContract fc = IFinancialContract(financialContractAddress); TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue); return fc.redeem(numTokens); } } interface IFinancialContract { function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn); function tokenCurrency() external returns (address); } /* MultiRoleTest contract. */ // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/MultiRole.sol"; // The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes. contract MultiRoleTest is MultiRole { function createSharedRole( uint256 roleId, uint256 managingRoleId, address[] calldata initialMembers ) external { _createSharedRole(roleId, managingRoleId, initialMembers); } function createExclusiveRole( uint256 roleId, uint256 managingRoleId, address initialMember ) external { _createExclusiveRole(roleId, managingRoleId, initialMember); } // solhint-disable-next-line no-empty-blocks function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {} } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/Testable.sol"; // TestableTest is derived from the abstract contract Testable for testing purposes. contract TestableTest is Testable { // solhint-disable-next-line no-empty-blocks constructor(address _timerAddress) public Testable(_timerAddress) {} function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) { // solhint-disable-next-line not-rely-on-time return (getCurrentTime(), now); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../interfaces/VaultInterface.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Mock for yearn-style vaults for use in tests. */ contract VaultMock is VaultInterface { IERC20 public override token; uint256 private pricePerFullShare = 0; constructor(IERC20 _token) public { token = _token; } function getPricePerFullShare() external view override returns (uint256) { return pricePerFullShare; } function setPricePerFullShare(uint256 _pricePerFullShare) external { pricePerFullShare = _pricePerFullShare; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Interface for Yearn-style vaults. * @dev This only contains the methods/events that we use in our contracts or offchain infrastructure. */ abstract contract VaultInterface { // Return the underlying token. function token() external view virtual returns (IERC20); // Gets the number of return tokens that a "share" of this vault is worth. function getPricePerFullShare() external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Implements only the required ERC20 methods. This contract is used * test how contracts handle ERC20 contracts that have not implemented `decimals()` * @dev Mostly copied from Consensys EIP-20 implementation: * https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol */ contract BasicERC20 is IERC20 { uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; uint256 private _totalSupply; constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; _totalSupply = _initialAmount; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function transfer(address _to, uint256 _value) public override returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) public override returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view override returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public override returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { return allowed[_owner][_spender]; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../ResultComputation.sol"; import "../../../common/implementation/FixedPoint.sol"; // Wraps the library ResultComputation for testing purposes. contract ResultComputationTest { using ResultComputation for ResultComputation.Data; ResultComputation.Data public data; function wrapAddVote(int256 votePrice, uint256 numberTokens) external { data.addVote(votePrice, FixedPoint.Unsigned(numberTokens)); } function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) { return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold)); } function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) { return data.wasVoteCorrect(revealHash); } function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) { return data.getTotalCorrectlyVotedTokens().rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../Voting.sol"; import "../../../common/implementation/FixedPoint.sol"; // Test contract used to access internal variables in the Voting contract. contract VotingTest is Voting { constructor( uint256 _phaseLength, FixedPoint.Unsigned memory _gatPercentage, FixedPoint.Unsigned memory _inflationRate, uint256 _rewardsExpirationTimeout, address _votingToken, address _finder, address _timerAddress ) public Voting( _phaseLength, _gatPercentage, _inflationRate, _rewardsExpirationTimeout, _votingToken, _finder, _timerAddress ) {} function getPendingPriceRequestsArray() external view returns (bytes32[] memory) { return pendingPriceRequests; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract UnsignedFixedPointTest { using FixedPoint for FixedPoint.Unsigned; using FixedPoint for uint256; using SafeMath for uint256; function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) { return FixedPoint.fromUnscaledUint(a).rawValue; } function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isEqual(b); } function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b)); } function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Unsigned(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b)); } function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b)); } function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) { return FixedPoint.Unsigned(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Unsigned(b)); } function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Unsigned(b)); } function wrapMin(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue; } function wrapMax(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue; } function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).add(b).rawValue; } function wrapSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).sub(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.sub(FixedPoint.Unsigned(b)).rawValue; } function wrapMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue; } function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mul(b).rawValue; } function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).mulCeil(b).rawValue; } function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue; } function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).div(b).rawValue; } function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).divCeil(b).rawValue; } // The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) { return a.div(FixedPoint.Unsigned(b)).rawValue; } // The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(uint256 a, uint256 b) external pure returns (uint256) { return FixedPoint.Unsigned(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; import "../implementation/FixedPoint.sol"; // Wraps the FixedPoint library for testing purposes. contract SignedFixedPointTest { using FixedPoint for FixedPoint.Signed; using FixedPoint for int256; using SafeMath for int256; function wrapFromSigned(int256 a) external pure returns (uint256) { return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue; } function wrapFromUnsigned(uint256 a) external pure returns (int256) { return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue; } function wrapFromUnscaledInt(int256 a) external pure returns (int256) { return FixedPoint.fromUnscaledInt(a).rawValue; } function wrapIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b)); } function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isEqual(b); } function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b)); } function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThan(b); } function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isGreaterThanOrEqual(b); } function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThan(FixedPoint.Signed(b)); } function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isGreaterThanOrEqual(FixedPoint.Signed(b)); } function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b)); } function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThan(b); } function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) { return FixedPoint.Signed(a).isLessThanOrEqual(b); } function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThan(FixedPoint.Signed(b)); } function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) { return a.isLessThanOrEqual(FixedPoint.Signed(b)); } function wrapMin(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue; } function wrapMax(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue; } function wrapAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).add(b).rawValue; } function wrapSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSub(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).sub(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) { return a.sub(FixedPoint.Signed(b)).rawValue; } function wrapMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue; } function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedMul(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mul(b).rawValue; } function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue; } function wrapDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue; } function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).div(b).rawValue; } function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) { return FixedPoint.Signed(a).divAwayFromZero(b).rawValue; } // The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) { return a.div(FixedPoint.Signed(b)).rawValue; } // The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly. function wrapPow(int256 a, uint256 b) external pure returns (int256) { return FixedPoint.Signed(a).pow(b).rawValue; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../../common/implementation/FixedPoint.sol"; /** * @title Simple Perpetual Mock to serve trivial functions */ contract PerpetualMock { struct FundingRate { FixedPoint.Signed rate; bytes32 identifier; FixedPoint.Unsigned cumulativeMultiplier; uint256 updateTime; uint256 applicationTime; uint256 proposalTime; } using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; FundingRate public fundingRate; // Interface functions required to be implemented in order for an instance of this contract to be passed into the // off-chain FinancialContractClient helper module: FixedPoint.Unsigned public collateralRequirement; uint256 public liquidationLiveness; FixedPoint.Unsigned public cumulativeFeeMultiplier; mapping(address => uint256) public positions; mapping(address => uint256) public liquidations; event NewSponsor(address indexed sponsor); event EndedSponsorPosition(); event LiquidationCreated(); function getCurrentTime() public view returns (uint256) { return now; } // Public methods that are useful for tests: function setFundingRate(FundingRate memory _fundingRate) external { fundingRate = _fundingRate; } function applyFundingRate() external { fundingRate.applicationTime = block.timestamp; // Simplified rate calcualtion. // multiplier = multiplier * (1 + rate) fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul( FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate)) ); } }
Creates an instance of expiring multi party and registers it within the registry. params is a `ConstructorParams` object from ExpiringMultiParty. return address of the deployed ExpiringMultiParty contract./ Create a new synthetic token using the params. If the collateral token does not have a `decimals()` method, then a default precision of 18 will be applied to the newly created synthetic token. Give permissions to new derivative contract and then hand over ownership.
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) { require(bytes(params.syntheticName).length != 0, "Missing synthetic name"); require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol"); TokenFactory tf = TokenFactory(tokenFactoryAddress); uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress); ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals); address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency)); tokenCurrency.addMinter(derivative); tokenCurrency.addBurner(derivative); tokenCurrency.resetOwner(derivative); _registerContract(new address[](0), derivative); emit CreatedExpiringMultiParty(derivative, msg.sender); return derivative; }
99,860
// SPDX-License-Identifier: AGPL-3.0-or-later /// DssProxyActionsCropper.sol // Copyright (C) 2018-2020 Maker Ecosystem Growth Holdings, INC. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom(address, address, uint256) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); } interface CropperLike { function getOrCreateProxy(address) external returns (address); function join(address, address, uint256) external; function exit(address, address, uint256) external; function flee(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function quit(bytes32, address, address) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function hope(address) external; function nope(address) external; function flux(bytes32, address, address, uint256) external; } interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function ilk() external returns (bytes32); function bonus() external returns (GemLike); } interface DaiJoinLike { function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } interface EndLike { function fix(bytes32) external view returns (uint256); function cash(bytes32, uint256) external; function free(bytes32) external; function pack(uint256) external; function skim(bytes32, address) external; } interface JugLike { function drip(bytes32) external returns (uint256); } interface HopeLike { function hope(address) external; function nope(address) external; } interface CdpRegistryLike { function owns(uint256) external view returns (address); function ilks(uint256) external view returns (bytes32); function open(bytes32, address) external returns (uint256); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; address immutable public vat; address immutable public cropper; address immutable public cdpRegistry; constructor(address vat_, address cropper_, address cdpRegistry_) public { vat = vat_; cropper = cropper_; cdpRegistry = cdpRegistry_; } // Internal functions function _mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address daiJoin, address u, uint256 wad) public { GemLike dai = DaiJoinLike(daiJoin).dai(); // Gets DAI from the user's wallet dai.transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount dai.approve(daiJoin, wad); // Joins DAI into the vat DaiJoinLike(daiJoin).join(u, wad); } } contract DssProxyActionsCropper is Common { constructor(address vat_, address cropper_, address cdpRegistry_) public Common(vat_, cropper_, cdpRegistry_) {} // Internal functions function _sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function _divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x != 0 ? ((x - 1) / y) + 1 : 0; } function _toInt256(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function _convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we // need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = _mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address jug, address u, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(u); // If there was already enough DAI in the vat balance, just exits it without adding more debt uint256 rad = _mul(wad, RAY); if (dai < rad) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = _toInt256(_divup(rad - dai, rate)); // safe since dai < rad } } function _getWipeDart( uint256 dai, address u, bytes32 ilk ) internal returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, CropperLike(cropper).getOrCreateProxy(u)); // Uses the whole dai balance in the vat to reduce the debt dart = _toInt256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), // otherwise uses its value dart = uint256(dart) <= art ? - dart : - _toInt256(art); } function _getWipeAllWad( address u, address urp, bytes32 ilk ) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urp); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(u); // If there was already enough DAI in the vat balance, no need to join more uint256 debt = _mul(art, rate); if (debt > dai) { wad = _divup(debt - dai, RAY); // safe since debt > dai } } function _frob( bytes32 ilk, address u, int256 dink, int256 dart ) internal { CropperLike(cropper).frob(ilk, u, u, u, dink, dart); } function _ethJoin_join(address ethJoin, address u) internal { GemLike gem = GemJoinLike(ethJoin).gem(); // Wraps ETH in WETH gem.deposit{value: msg.value}(); // Approves adapter to take the WETH amount gem.approve(cropper, msg.value); // Joins WETH collateral into the vat CropperLike(cropper).join(ethJoin, u, msg.value); } function _gemJoin_join(address gemJoin, address u, uint256 amt) internal { GemLike gem = GemJoinLike(gemJoin).gem(); // Gets token from the user's wallet gem.transferFrom(msg.sender, address(this), amt); // Approves adapter to take the token amount gem.approve(cropper, amt); // Joins token collateral into the vat CropperLike(cropper).join(gemJoin, u, amt); } // Public functions function transfer(address gem, address dst, uint256 amt) external { GemLike(gem).transfer(dst, amt); } function hope( address obj, address usr ) external { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) external { HopeLike(obj).nope(usr); } function open( bytes32 ilk, address usr ) external returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, usr); } function lockETH( address ethJoin, uint256 cdp ) external payable { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat _ethJoin_join(ethJoin, owner); // Locks WETH amount into the CDP _frob(CdpRegistryLike(cdpRegistry).ilks(cdp), owner, _toInt256(msg.value), 0); } function lockGem( address gemJoin, uint256 cdp, uint256 amt ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); // Takes token amount from user's wallet and joins into the vat _gemJoin_join(gemJoin, owner, amt); // Locks token amount into the CDP _frob(CdpRegistryLike(cdpRegistry).ilks(cdp), owner, _toInt256(_convertTo18(gemJoin, amt)), 0); } function freeETH( address ethJoin, uint256 cdp, uint256 wad ) external { // Unlocks WETH amount from the CDP _frob( CdpRegistryLike(cdpRegistry).ilks(cdp), CdpRegistryLike(cdpRegistry).owns(cdp), -_toInt256(wad), 0 ); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address gemJoin, uint256 cdp, uint256 amt ) external { // Unlocks token amount from the CDP _frob( CdpRegistryLike(cdpRegistry).ilks(cdp), CdpRegistryLike(cdpRegistry).owns(cdp), -_toInt256(_convertTo18(gemJoin, amt)), 0 ); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function exitETH( address ethJoin, uint256 cdp, uint256 wad ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(ethJoin).ilk(), "wrong-ilk"); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address gemJoin, uint256 cdp, uint256 amt ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function fleeETH( address ethJoin, uint256 cdp, uint256 wad ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(ethJoin).ilk(), "wrong-ilk"); // Exits WETH to proxy address as a token CropperLike(cropper).flee(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function fleeGem( address gemJoin, uint256 cdp, uint256 amt ) external { require(CdpRegistryLike(cdpRegistry).owns(cdp) == address(this), "wrong-cdp"); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); // Exits token amount to the user's wallet as a token CropperLike(cropper).flee(gemJoin, msg.sender, amt); } function draw( address jug, address daiJoin, uint256 cdp, uint256 wad ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Generates debt in the CDP _frob(ilk, owner, 0, _getDrawDart(jug, owner, ilk, wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function wipe( address daiJoin, uint256 cdp, uint256 wad ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wad); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP _frob( ilk, owner, 0, _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); } function wipeAll( address daiJoin, uint256 cdp ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP _frob(ilk, owner, 0, -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); } function lockETHAndDraw( address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat _ethJoin_join(ethJoin, owner); // Locks WETH amount into the CDP and generates debt _frob( ilk, owner, _toInt256(msg.value), _getDrawDart( jug, owner, ilk, wadD ) ); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD ) public payable returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, address(this)); lockETHAndDraw(jug, ethJoin, daiJoin, cdp, wadD); } function lockGemAndDraw( address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD ) public { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Takes token amount from user's wallet and joins into the vat _gemJoin_join(gemJoin, owner, amtC); // Locks token amount into the CDP and generates debt _frob( ilk, owner, _toInt256(_convertTo18(gemJoin, amtC)), _getDrawDart( jug, owner, ilk, wadD ) ); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 amtC, uint256 wadD ) public returns (uint256 cdp) { cdp = CdpRegistryLike(cdpRegistry).open(ilk, address(this)); lockGemAndDraw(jug, gemJoin, daiJoin, cdp, amtC, wadD); } function wipeAndFreeETH( address ethJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wadD); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks WETH amount from it _frob( ilk, owner, -_toInt256(wadC), _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAllAndFreeETH( address ethJoin, address daiJoin, uint256 cdp, uint256 wadC ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks WETH amount from it _frob(ilk, owner, -_toInt256(wadC), -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAndFreeGem( address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, wadD); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks token amount from it _frob( ilk, owner, -_toInt256(_convertTo18(gemJoin, amtC)), _getWipeDart( VatLike(vat).dai(owner), owner, ilk ) ); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amtC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amtC); } function wipeAllAndFreeGem( address gemJoin, address daiJoin, uint256 cdp, uint256 amtC ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); bytes32 ilk = CdpRegistryLike(cdpRegistry).ilks(cdp); address urp = CropperLike(cropper).getOrCreateProxy(owner); (, uint256 art) = VatLike(vat).urns(ilk, urp); // Joins DAI amount into the vat daiJoin_join(daiJoin, owner, _getWipeAllWad(owner, urp, ilk)); // Allows cropper to access to proxy's DAI balance in the vat VatLike(vat).hope(cropper); // Paybacks debt to the CDP and unlocks token amount from it _frob(ilk, owner, -_toInt256(_convertTo18(gemJoin, amtC)), -_toInt256(art)); // Denies cropper to access to proxy's DAI balance in the vat after execution VatLike(vat).nope(cropper); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amtC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amtC); } function crop( address gemJoin, uint256 cdp ) external { address owner = CdpRegistryLike(cdpRegistry).owns(cdp); require(CdpRegistryLike(cdpRegistry).ilks(cdp) == GemJoinLike(gemJoin).ilk(), "wrong-ilk"); CropperLike(cropper).join(gemJoin, owner, 0); GemLike bonus = GemJoinLike(gemJoin).bonus(); bonus.transfer(msg.sender, bonus.balanceOf(address(this))); } } contract DssProxyActionsEndCropper is Common { constructor(address vat_, address cropper_, address cdpRegistry_) public Common(vat_, cropper_, cdpRegistry_) {} // Internal functions function _free( address end, address u, bytes32 ilk ) internal returns (uint256 ink) { address urp = CropperLike(cropper).getOrCreateProxy(u); uint256 art; (ink, art) = VatLike(vat).urns(ilk, urp); // If CDP still has debt, it needs to be paid if (art > 0) { EndLike(end).skim(ilk, urp); (ink,) = VatLike(vat).urns(ilk, urp); } // Approves the cropper to transfer the position to proxy's address in the vat VatLike(vat).hope(cropper); // Transfers position from CDP to the proxy address CropperLike(cropper).quit(ilk, u, address(this)); // Denies cropper to access to proxy's position in the vat after execution VatLike(vat).nope(cropper); // Frees the position and recovers the collateral in the vat registry EndLike(end).free(ilk); // Fluxs to the proxy's cropper proxy, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), urp, ink ); } // Public functions function freeETH( address ethJoin, address end, uint256 cdp ) external { // Frees the position through the end contract uint256 wad = _free(end, CdpRegistryLike(cdpRegistry).owns(cdp), CdpRegistryLike(cdpRegistry).ilks(cdp)); // Exits WETH amount to proxy address as a token CropperLike(cropper).exit(ethJoin, address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address gemJoin, address end, uint256 cdp ) external { // Frees the position through the end contract uint256 wad = _free(end, CdpRegistryLike(cdpRegistry).owns(cdp), CdpRegistryLike(cdpRegistry).ilks(cdp)); // Exits token amount to the user's wallet as a token uint256 amt = wad / 10 ** (18 - GemJoinLike(gemJoin).dec()); // Exits token amount to proxy address as a token CropperLike(cropper).exit(gemJoin, address(this), amt); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).gem().transfer(msg.sender, amt); } function pack( address daiJoin, address end, uint256 wad ) external { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Approves the end to take out DAI from the proxy's balance in the vat if (VatLike(vat).can(address(this), address(end)) == 0) { VatLike(vat).hope(end); } EndLike(end).pack(wad); } function cashETH( address ethJoin, address end, uint256 wad ) external { bytes32 ilk = GemJoinLike(ethJoin).ilk(); EndLike(end).cash(ilk, wad); uint256 wadC = _mul(wad, EndLike(end).fix(ilk)) / RAY; // Flux to the proxy's UrnProxy in cropper, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), CropperLike(cropper).getOrCreateProxy(address(this)), wadC ); // Exits WETH amount to proxy address as a token CropperLike(cropper).flee(ethJoin, address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function cashGem( address gemJoin, address end, uint256 wad ) external { bytes32 ilk = GemJoinLike(gemJoin).ilk(); EndLike(end).cash(ilk, wad); uint256 wadC = _mul(wad, EndLike(end).fix(ilk)) / RAY; // Flux to the proxy's UrnProxy in cropper, so it can be pulled out with the managed gem join VatLike(vat).flux( ilk, address(this), CropperLike(cropper).getOrCreateProxy(address(this)), wadC ); // Exits token amount to the user's wallet as a token uint256 amt = wadC / 10 ** (18 - GemJoinLike(gemJoin).dec()); CropperLike(cropper).flee(gemJoin, msg.sender, amt); } }
Joins DAI amount into the vat Approves the end to take out DAI from the proxy's balance in the vat
function pack( address daiJoin, address end, uint256 wad ) external { daiJoin_join(daiJoin, address(this), wad); if (VatLike(vat).can(address(this), address(end)) == 0) { VatLike(vat).hope(end); } EndLike(end).pack(wad); }
52,463
/** *Submitted for verification at Etherscan.io on 2020-06-30 */ pragma solidity 0.5.17; interface IMoloch { function getProposalFlags(uint256 proposalId) external view returns (bool[6] memory); function setMinion(address minion) external; function submitProposal( address applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details ) external returns (uint256); function withdrawBalance(address token, uint256 amount) external; } contract Minion { IMoloch public moloch; address private molochDepositToken; bytes32 public constant MINION_ACTION_DETAILS = 0x7b69734d696e696f6e3a20747275652c207469746c653a4d494e494f4e2c2064; mapping(uint256 => Action) public actions; // proposalId => Action struct Action { uint256 value; address to; address proposer; bool executed; bytes data; } event ActionProposed(uint256 proposalId, address proposer); event ActionExecuted(uint256 proposalId, address executor); constructor(address _moloch, address _molochDepositToken) public { moloch = IMoloch(_moloch); molochDepositToken = _molochDepositToken; moloch.setMinion(address(this)); } // withdraw funds from the moloch function doWithdraw(address _token, uint256 _amount) public { moloch.withdrawBalance(_token, _amount); } function proposeAction( address _actionTo, uint256 _actionValue, bytes memory _actionData, bytes32 _description ) public returns (uint256) { // No calls to zero address allows us to check that minion submitted // the proposal without getting the proposal struct from the moloch require(_actionTo != address(0), "invalid _actionTo"); bytes32 details = keccak256(abi.encodePacked(MINION_ACTION_DETAILS, _description, '"}')); uint256 proposalId = moloch.submitProposal( address(this), 0, 0, 0, molochDepositToken, 0, molochDepositToken, details ); Action memory action = Action({ value: _actionValue, to: _actionTo, proposer: msg.sender, executed: false, data: _actionData }); actions[proposalId] = action; emit ActionProposed(proposalId, msg.sender); return proposalId; } function executeAction(uint256 _proposalId) public returns (bytes memory) { Action memory action = actions[_proposalId]; bool[6] memory flags = moloch.getProposalFlags(_proposalId); // minion did not submit this proposal require(action.to != address(0), "invalid _proposalId"); // can't call arbitrary functions on parent moloch require(action.to != address(moloch), "invalid target"); require(!action.executed, "action executed"); require(address(this).balance >= action.value, "insufficient eth"); require(flags[2], "proposal not passed"); // execute call actions[_proposalId].executed = true; (bool success, bytes memory retData) = (false, bytes(msg.data)); action.to.call.value(action.value)(action.data); //inject UNHANDLED EXCEPTION require(success, "call failure"); emit ActionExecuted(_proposalId, msg.sender); return retData; } function() external payable {} }
No calls to zero address allows us to check that minion submitted the proposal without getting the proposal struct from the moloch
function proposeAction( address _actionTo, uint256 _actionValue, bytes memory _actionData, bytes32 _description ) public returns (uint256) { require(_actionTo != address(0), "invalid _actionTo"); bytes32 details = keccak256(abi.encodePacked(MINION_ACTION_DETAILS, _description, '"}')); uint256 proposalId = moloch.submitProposal( address(this), 0, 0, 0, molochDepositToken, 0, molochDepositToken, details );
5,342,594
pragma solidity ^0.4.11; contract SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } } // contract ERC20 { // function totalSupply() constant returns (uint supply); // function balanceOf( address who ) constant returns (uint value); // function allowance( address owner, address spender ) constant returns (uint _allowance); // function transfer( address to, uint value) returns (bool ok); // function transferFrom( address from, address to, uint value) returns (bool ok); // function approve( address spender, uint value ) returns (bool ok); // event Transfer( address indexed from, address indexed to, uint value); // event Approval( address indexed owner, address indexed spender, uint value); // } //https://github.com/ethereum/ethereum-org/blob/master/solidity/token-erc20.sol interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value >= balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } contract Erc20Dist is SafeMath { TokenERC20 public _erc20token; //被操作的erc20代币 address public _ownerDist;// 这个合约最高权限人,开始是创建者,可以移交给他人 uint256 public _distDay;//发布时间 uint256 public _mode = 0;//模型是1表示使用模式1,2表示使用模式2 uint256 public _lockAllAmount;//锁仓的总量 struct Detail{//发放情况详情结构体声明 address founder;//创始人地址 uint256 lockDay;//锁仓时间 uint256 lockPercent;//锁仓百分比数(0到100之间) uint256 distAmount;//总分配数量 uint256 lockAmount;//锁住的代币总量 uint256 initAmount;//初始款的代币量 uint256 distRate;//锁仓解锁后每天分配代币百分比数(按锁住的总额算,0到100之间) uint256 oneDayTransferAmount;//锁仓解锁后每天应发放的代币数量 uint256 transferedAmount;//已转账代币数量 uint256 lastTransferDay;//最后一笔代币分配的时间 bool isFinish;// 是否本人都发放完成 bool isCancelDist;//是否同意撤销发行 } Detail private detail = Detail(address(0),0,0,0,0,0,0,0,0,0, false, false);//中间变量初始化,用来在函数中临时承接计算结果,以便传送给_details Detail[] public _details;//发放情况详情列表,并初始化为空值 uint256 public _detailsLength = 0;//发放详情长度 bool public _fDist = false;// 是否已经发布过的标识符号 bool public _fConfig = false;// 是否已经配置过的标识符号 bool public _fFinish = false;// 是否所有人都发放完成 bool public _fCancelDist = false;// 是否撤销发行 function Erc20Dist() public { _ownerDist = msg.sender; // 默认创建者为权限最高人 } function () public{}//callback函数,由于合约没有eth价值传入,所以没有什么安全问题 // 设置合约所有者 function setOwner(address owner_) public { require (msg.sender == _ownerDist, "you must _ownerDist");// 必须原来所有者授权 require(_fDist == false, "not dist"); // 必须还没开始发布 require(_fConfig == false, "not config");// 必须还没配置过 _ownerDist = owner_; } //设置操作代币函数 function setErc20(TokenERC20 erc20Token) public { require (msg.sender == _ownerDist, "you must _ownerDist"); require(address(_erc20token) == address(0),"you have set erc20Token");//必须之前没有设置过 require(erc20Token.balanceOf(address(this)) > 0, "this contract must own tokens"); _erc20token = erc20Token;//在全局设置erc20代币 _lockAllAmount = erc20Token.balanceOf(address(this)); } // 撤销发行,必须所有参与人同意,才能撤销发行 function cancelDist() public { require(_fDist == true, "must dist"); // 必须发布 require(_fCancelDist == false, "must not cancel dist"); // 循环判断是否 for(uint256 i=0;i<_details.length;i++){ // 判断是否发行者 if ( _details[i].founder == msg.sender ) { // 设置标志 _details[i].isCancelDist = true; break; } } // 更新状态 updateCancelDistFlag(); if (_fCancelDist == true) { require(_erc20token.balanceOf(address(this)) > 0, "must have balance"); // 返回所有代币给最高权限人 _erc20token.transfer( _ownerDist, _erc20token.balanceOf(address(this)) ); } } // 更新是否撤销发行标志 function updateCancelDistFlag() private { bool allCancelDist = true; for(uint256 i=0; i<_details.length; i++){ // 判断有没有人没撤销 if (_details[i].isCancelDist == false) { allCancelDist = false; break; } } // 更新合约完成标志 _fCancelDist = allCancelDist; } // 还没调用发行情况下,返还所有代币,到最高权限账号,并且清除配置 function clearConfig() public { require (msg.sender == _ownerDist, "you must _ownerDist"); require(_fDist == false, "not dist"); // 必须还没开始发布 require(address(_erc20token) != address(0),"you must set erc20Token");//必须之前设置过 require(_erc20token.balanceOf(address(this)) > 0, "must have balance"); // 返回所有代币给最高权限人 _erc20token.transfer( msg.sender, _erc20token.balanceOf(address(this)) ); // 清空变量 _lockAllAmount = 0; TokenERC20 nullErc20token; _erc20token = nullErc20token; Detail[] nullDetails; _details = nullDetails; _detailsLength = 0; _mode = 0; _fConfig = false; } // 客户之前多转到合约的币,可以通过这个接口,提取回最高权限人账号,但必须在合约执行完成之后 function withDraw() public { require (msg.sender == _ownerDist, "you must _ownerDist"); require(_fFinish == true, "dist must be finished"); // 合约必须执行完毕 require(address(_erc20token) != address(0),"you must set erc20Token");//必须之前设置过 require(_erc20token.balanceOf(address(this)) > 0, "must have balance"); // 返回所有代币给最高权限人 _erc20token.transfer( _ownerDist, _erc20token.balanceOf(address(this)) ); } //配置相关创始人及代币发放、锁仓信息等相关情况的函数。auth认证,必须是合约持有人才能进行该操作 function configContract(uint256 mode,address[] founders,uint256[] distWad18Amounts,uint256[] lockPercents,uint256[] lockDays,uint256[] distRates) public { //函数变量说明:founders(创始人地址列表), //distWad18Amounts(总发放数量列表(不输入18位小数位)), //lockPercents(锁仓百分比列表(值在0到100之间)), //lockDays(锁仓天数列表),distRates(每天发放数占锁仓总数的万分比数列表(值在0到10000之间)) require (msg.sender == _ownerDist, "you must _ownerDist"); require(mode==1||mode==2,"there is only mode 1 or 2");//只有模式1和2两种申领余款方式 _mode = mode;//将申领方式注册到全局 require(_fConfig == false,"you have configured it already");//必须还未配置过 require(address(_erc20token) != address(0), "you must setErc20 first");//必须已经设置好被操作erc20代币 require(founders.length!=0,"array length can not be zero");//创始人列表不能为空 require(founders.length==distWad18Amounts.length,"founders length dismatch distWad18Amounts length");//创始人列表长度必须等于发放数量列表长度 require(distWad18Amounts.length==lockPercents.length,"distWad18Amounts length dismatch lockPercents length");//发放数量列表长度必须等于锁仓百分比列表长度 require(lockPercents.length==lockDays.length,"lockPercents length dismatch lockDays length");//锁仓百分比列表长度必须等于锁仓天数列表长度 require(lockDays.length==distRates.length,"lockDays length dismatch distRates length");//锁仓百分比列表长度必须等于每日发放比率列表长度 //遍历 for(uint256 i=0;i<founders.length;i++){ require(distWad18Amounts[i]!=0,"dist token amount can not be zero");//确保发放数量不为0 for(uint256 j=0;j<i;j++){ require(founders[i]!=founders[j],"you could not give the same address of founders");//必须确保创始人中没有地址相同的 } } //以下为循环中服务全局变量的中间临时变量 uint256 totalAmount = 0;//发放代币总量 uint256 distAmount = 0;//给当前创始人发放代币量(带18位精度) uint256 oneDayTransferAmount = 0;//解锁后每天应发放的数量(将在后续进行计算) uint256 lockAmount = 0;//当前创始人锁住的代币量 uint256 initAmount = 0;//当前创始人初始款代币量 //遍历 for(uint256 k=0;k<lockPercents.length;k++){ require(lockPercents[k]<=100,"lockPercents unit must <= 100");//锁仓百分比数必须小于等于100 require(distRates[k]<=10000,"distRates unit must <= 10000");//发放万分比数必须小于等于10000 distAmount = mul(distWad18Amounts[k],10**18);//给当前创始人发放代币量(带18位精度) totalAmount = add(totalAmount,distAmount);//发放总量累加 lockAmount = div(mul(lockPercents[k],distAmount),100);//锁住的代币数量 initAmount = sub(distAmount, lockAmount);//初始款的代币数量 oneDayTransferAmount = div(mul(distRates[k],lockAmount),10000);//解锁后每天应发放的数量 //下面为中间变量detail的9个成员赋值 detail.founder = founders[k]; detail.lockDay = lockDays[k]; detail.lockPercent = lockPercents[k]; detail.distRate = distRates[k]; detail.distAmount = distAmount; detail.lockAmount = lockAmount; detail.initAmount = initAmount; detail.oneDayTransferAmount = oneDayTransferAmount; detail.transferedAmount = 0;//初始还未开始发放,所以已分配数量为0 detail.lastTransferDay = 0;//初始还未开始发放,最后的发放日设为0 detail.isFinish = false; detail.isCancelDist = false; //将赋好的中间信息压入全局信息列表_details _details.push(detail); } require(totalAmount <= _lockAllAmount, "distributed total amount should be equal lock amount");// 发行总量应该等于锁仓总量 require(totalAmount <= _erc20token.totalSupply(),"distributed total amount should be less than token totalSupply");//发放的代币总量必须小于总代币量 _detailsLength = _details.length; _fConfig = true;//配置完毕,将配置完成标识符设为真 _fFinish = false;// 默认没发放完成 _fCancelDist = false;// 撤销发行清空 } //开始发放函数,将未锁仓头款发放给个创始人,如果有锁仓天数为0的,将锁款的解锁后的头天代币也一同发放。auth认证,必须是合约持有人才能进行该操作 function startDistribute() public { require (msg.sender == _ownerDist, "you must _ownerDist"); require(_fDist == false,"you have distributed erc20token already");//必须还未初始发放过 require(_details.length != 0,"you have not configured");//必须还未配置过 _distDay = today();//将当前区块链系统时间记录为发放时间 uint256 initDistAmount=0;//以下循环中使用的当前创始人“初始发放代币量”临时变量 for(uint256 i=0;i<_details.length;i++){ initDistAmount = _details[i].initAmount;//首发量 if(_details[i].lockDay==0){//如果当前创始人锁仓天数为0 initDistAmount = add(initDistAmount, _details[i].oneDayTransferAmount);//初始发放代币量为首发量+一天的发放量 } _erc20token.transfer( _details[i].founder, initDistAmount ); _details[i].transferedAmount = initDistAmount;//已发放数量在全局细节中进行登记 _details[i].lastTransferDay =_distDay;//最新一次发放日期在全局细节中进行登记 } _fDist = true;//已初始发放标识符设为真 updateFinishFlag();// 更新下完成标志 } // 更新是否发行完成标志 function updateFinishFlag() private { // bool allFinish = true; for(uint256 i=0; i<_details.length; i++){ // 不需要锁仓的,直接设置完成 if (_details[i].lockPercent == 0) { _details[i].isFinish = true; continue; } // 有锁仓的,发行数量等于解锁数量,也设置完成 if (_details[i].distAmount == _details[i].transferedAmount) { _details[i].isFinish = true; continue; } allFinish = false; } // 更新合约完成标志 _fFinish = allFinish; } //模式1:任意人可调用该函数申领当天应发放额 function applyForTokenOneDay() public{ require(_mode == 1,"this function can be called only when _mode==1");//模式1下可调用 require(_distDay != 0,"you haven't distributed");//必须已经发布初始款了 require(_fFinish == false, "not finish");//必须合约还没执行完 require(_fCancelDist == false, "must not cancel dist"); uint256 daysAfterDist;//距离初始金发放时间 uint256 tday = today();//调用该函数时系统当前时间 for(uint256 i=0;i<_details.length;i++){ // 对于已经完成的可以pass if (_details[i].isFinish == true) { continue; } require(tday!=_details[i].lastTransferDay,"you have applied for todays token");//必须今天还未申领 daysAfterDist = sub(tday,_distDay);//计算距离初始金发放时间天数 if(daysAfterDist >= _details[i].lockDay){//距离发放日天数要大于等于锁仓天数 if(add(_details[i].transferedAmount, _details[i].oneDayTransferAmount) <= _details[i].distAmount){ //如果当前创始人剩余的发放数量大于等于每天应发放数量,则将当天应发放数量发给他 _erc20token.transfer( _details[i].founder, _details[i].oneDayTransferAmount ); //已发放数量在全局细节中进行登记更新 _details[i].transferedAmount = add(_details[i].transferedAmount, _details[i].oneDayTransferAmount); } else if(_details[i].transferedAmount < _details[i].distAmount){ //否则,如果已发放数量未达到锁仓应发总量,则将当前创始人剩余的应发放代币都发放给他 _erc20token.transfer( _details[i].founder, sub( _details[i].distAmount, _details[i].transferedAmount) ); //已发放数量在全局细节中进行登记更新 _details[i].transferedAmount = _details[i].distAmount; } //最新一次发放日期在全局细节中进行登记更新 _details[i].lastTransferDay = tday; } } // 更新下完成标志 updateFinishFlag(); } ///模式2:任意人可调用该函数补领到当前时间应该拥有但未发的代币 function applyForToken() public { require(_mode == 2,"this function can be called only when _mode==2");//模式2下可调用 require(_distDay != 0,"you haven't distributed");//必须已经发布初始款了 require(_fFinish == false, "not finish");//必须合约还没执行完 require(_fCancelDist == false, "must not cancel dist"); uint256 daysAfterDist;//距离初始金发放时间 uint256 expectAmount;//下面循环中当前创始人到今天为止应该被发放的数量 uint256 tday = today();//调用该函数时系统当前时间 uint256 expectReleaseTimesNoLimit = 0;//解锁后到今天为止应该放的尾款次数(不考虑已放完款的情况) for(uint256 i=0;i<_details.length;i++){ // 对于已经完成的可以pass if (_details[i].isFinish == true) { continue; } //必须今天还未申领 require(tday!=_details[i].lastTransferDay,"you have applied for todays token"); daysAfterDist = sub(tday,_distDay);//计算距离初始金发放时间天数 if(daysAfterDist >= _details[i].lockDay){//距离发放日天数要大于等于锁仓天数 expectReleaseTimesNoLimit = add(sub(daysAfterDist,_details[i].lockDay),1);//解锁后到今天为止应该放的尾款次数 //到目前为止应该发放的总数=((应该释放款的次数x每次应该释放的币数)+初始款数量)与 当前创始人应得总发放数量 中的较小值 //因为释放款次数可能很大了,超过领完时间了 expectAmount = min(add(mul(expectReleaseTimesNoLimit,_details[i].oneDayTransferAmount),_details[i].initAmount),_details[i].distAmount); //将欠下的代币统统发放给当前创始人 _erc20token.transfer( _details[i].founder, sub(expectAmount, _details[i].transferedAmount) ); //已发放数量在全局细节中进行登记更新 _details[i].transferedAmount = expectAmount; //最新一次发放日期在全局细节中进行登记更新 _details[i].lastTransferDay = tday; } } // 更新下完成标志 updateFinishFlag(); } //一天进行计算 function today() public constant returns (uint256) { return div(time(), 24 hours);//24 hours } //获取当前系统时间 function time() public constant returns (uint256) { return block.timestamp; } }
模式2:任意人可调用该函数补领到当前时间应该拥有但未发的代币
function applyForToken() public { require(_fCancelDist == false, "must not cancel dist"); updateFinishFlag(); for(uint256 i=0;i<_details.length;i++){ if (_details[i].isFinish == true) { continue; } _details[i].founder, sub(expectAmount, _details[i].transferedAmount) ); } for(uint256 i=0;i<_details.length;i++){ if (_details[i].isFinish == true) { continue; } _details[i].founder, sub(expectAmount, _details[i].transferedAmount) ); } require(tday!=_details[i].lastTransferDay,"you have applied for todays token"); expectAmount = min(add(mul(expectReleaseTimesNoLimit,_details[i].oneDayTransferAmount),_details[i].initAmount),_details[i].distAmount); _erc20token.transfer( _details[i].transferedAmount = expectAmount; _details[i].lastTransferDay = tday; }
192,575
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // 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))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} 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, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: 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), "ECDSA: invalid signature"); return signer; } /** * @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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.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 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.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 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.7.0; abstract contract Proxied { /// @notice to be used by initialisation / postUpgrade function so that only the owner can execute them /// It also allows these functions to be called inside a contructor when the contract /// is meant to be used without proxy modifier proxied() { address ownerAddress = _owner(); // With hardhat-deploy proxies // the ownerAddress is zero only for the implementation contract // if the implementation contract want to be used as standalone // it simply has to execute the `proxied` function // This ensure the ownerAddress is never zero post deployment if (ownerAddress == address(0)) { // ensure can not be called twice when used outside of proxy : no admin // solhint-disable-next-line security/no-inline-assembly assembly { sstore( 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ) } } else { require(msg.sender == ownerAddress); } _; } modifier onlyOwner() { require(msg.sender == _owner(), "NOT_AUTHORIZED"); _; } function _owner() internal view returns (address ownerAddress) { // solhint-disable-next-line security/no-inline-assembly assembly { ownerAddress := sload(0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103) } } } // SPDX-License-Identifier: MIT pragma solidity 0.7.1; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol"; // only partially implemented for efficiency and simplicity import "@openzeppelin/contracts/introspection/IERC165.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; abstract contract ERC721Base is IERC165, IERC721 { using Address for address; using EnumerableSet for EnumerableSet.UintSet; bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; bytes4 internal constant ERC165ID = 0x01ffc9a7; uint256 internal constant OPERATOR_FLAG = (2**255); uint256 internal constant BURN_FLAG = (2**254); uint256 internal _supply; mapping (uint256 => uint256) internal _owners; mapping (address => EnumerableSet.UintSet) internal _holderTokens; mapping(address => mapping(address => bool)) internal _operatorsForAll; mapping(uint256 => address) internal _operators; /// @notice Approve an operator to spend tokens on the senders behalf. /// @param operator The address receiving the approval. /// @param id The id of the token. function approve(address operator, uint256 id) external override { address owner = _ownerOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == msg.sender || _operatorsForAll[owner][msg.sender], "UNAUTHORIZED_APPROVAL"); _approveFor(owner, operator, id); } /// @notice Transfer a token between 2 addresses. /// @param from The sender of the token. /// @param to The recipient of the token. /// @param id The id of the token. function transferFrom( address from, address to, uint256 id ) external override { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == from, "NOT_OWNER"); require(to != address(0), "NOT_TO_ZEROADDRESS"); if (msg.sender != from) { require( _operatorsForAll[from][msg.sender] || (operatorEnabled && _operators[id] == msg.sender), "UNAUTHORIZED_TRANSFER" ); } _transferFrom(from, to, id); } /// @notice Transfer a token between 2 addresses letting the receiver know of the transfer. /// @param from The send of the token. /// @param to The recipient of the token. /// @param id The id of the token. function safeTransferFrom( address from, address to, uint256 id ) external override { safeTransferFrom(from, to, id, ""); } /// @notice Set the approval for an operator to manage all the tokens of the sender. /// @param operator The address receiving the approval. /// @param approved The determination of the approval. function setApprovalForAll(address operator, bool approved) external override { _setApprovalForAll(msg.sender, operator, approved); } /// @notice Get the number of tokens owned by an address. /// @param owner The address to look for. /// @return balance The number of tokens owned by the address. function balanceOf(address owner) external view override returns (uint256 balance) { require(owner != address(0), "ZERO_ADDRESS_OWNER"); balance = _holderTokens[owner].length(); } /// @notice Get the owner of a token. /// @param id The id of the token. /// @return owner The address of the token owner. function ownerOf(uint256 id) external view override returns (address owner) { owner = _ownerOf(id); require(owner != address(0), "NONEXISTANT_TOKEN"); } function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256) { return _holderTokens[owner].at(index); } function totalSupply() external view returns (uint256) { return _supply; } /// @notice Get the approved operator for a specific token. /// @param id The id of the token. /// @return The address of the operator. function getApproved(uint256 id) external view override returns (address) { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); if (operatorEnabled) { return _operators[id]; } else { return address(0); } } /// @notice Check if the sender approved the operator. /// @param owner The address of the owner. /// @param operator The address of the operator. /// @return isOperator The status of the approval. function isApprovedForAll(address owner, address operator) external view override returns (bool isOperator) { return _operatorsForAll[owner][operator]; } /// @notice Transfer a token between 2 addresses letting the receiver knows of the transfer. /// @param from The sender of the token. /// @param to The recipient of the token. /// @param id The id of the token. /// @param data Additional data. function safeTransferFrom( address from, address to, uint256 id, bytes memory data ) public override { (address owner, bool operatorEnabled) = _ownerAndOperatorEnabledOf(id); require(owner != address(0), "NONEXISTENT_TOKEN"); require(owner == from, "NOT_OWNER"); require(to != address(0), "NOT_TO_ZEROADDRESS"); if (msg.sender != from) { require( _operatorsForAll[from][msg.sender] || (operatorEnabled && _operators[id] == msg.sender), "UNAUTHORIZED_TRANSFER" ); } _transferFrom(from, to, id); if (to.isContract()) { require(_checkOnERC721Received(msg.sender, from, to, id, data), "ERC721_TRANSFER_REJECTED"); } } /// @notice Check if the contract supports an interface. /// 0x01ffc9a7 is ERC165. /// 0x80ac58cd is ERC721 /// 0x780e9d63 is for ERC721 enumerable /// @param id The id of the interface. /// @return Whether the interface is supported. function supportsInterface(bytes4 id) public pure virtual override returns (bool) { return id == 0x01ffc9a7 || id == 0x80ac58cd || id == 0x780e9d63; } function _transferFrom( address from, address to, uint256 id ) internal { _holderTokens[from].remove(id); _holderTokens[to].add(id); _owners[id] = uint256(to); emit Transfer(from, to, id); } /// @dev See approve. function _approveFor( address owner, address operator, uint256 id ) internal { if (operator == address(0)) { _owners[id] = uint256(owner); } else { _owners[id] = OPERATOR_FLAG | uint256(owner); _operators[id] = operator; } emit Approval(owner, operator, id); } /// @dev See setApprovalForAll. function _setApprovalForAll( address sender, address operator, bool approved ) internal { _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @dev Check if receiving contract accepts erc721 transfers. /// @param operator The address of the operator. /// @param from The from address, may be different from msg.sender. /// @param to The adddress we want to transfer to. /// @param id The id of the token we would like to transfer. /// @param data Any additional data to send with the transfer. /// @return Whether the expected value of 0x150b7a02 is returned. function _checkOnERC721Received( address operator, address from, address to, uint256 id, bytes memory data ) internal returns (bool) { bytes4 retval = IERC721Receiver(to).onERC721Received(operator, from, id, data); return (retval == ERC721_RECEIVED); } /// @dev See ownerOf function _ownerOf(uint256 id) internal view returns (address owner) { owner = address(_owners[id]); require(owner != address(0), "NOT_EXIST"); } /// @dev Get the owner and operatorEnabled status of a token. /// @param id The token to query. /// @return owner The owner of the token. /// @return operatorEnabled Whether or not operators are enabled for this token. function _ownerAndOperatorEnabledOf(uint256 id) internal view returns (address owner, bool operatorEnabled) { uint256 data = _owners[id]; owner = address(data); operatorEnabled = (data & OPERATOR_FLAG) == OPERATOR_FLAG; } function _mint(uint256 id, address to) internal { require(to != address(0), "NOT_TO_ZEROADDRESS"); uint256 data = _owners[id]; require(data == 0, "ALREADY_MINTED"); _holderTokens[to].add(id); _owners[id] = uint256(to); _supply ++; emit Transfer(address(0), to, id); } function _burn(uint256 id) internal { uint256 data = _owners[id]; require(data != 0, "NOT_EXIST"); require(data & BURN_FLAG == 0, "ALREADY_BURNT"); address owner = address(data); require(msg.sender == owner, "NOT_OWNER"); _holderTokens[owner].remove(id); _owners[id] = BURN_FLAG; _supply --; emit Transfer(msg.sender, address(0), id); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.1; pragma experimental ABIEncoderV2; // solhint-disable quotes import "./ERC721Base.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol"; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "hardhat-deploy/solc_0.7/proxy/Proxied.sol"; contract MandalaToken is ERC721Base, IERC721Metadata, Proxied { using EnumerableSet for EnumerableSet.UintSet; using ECDSA for bytes32; // solhint-disable-next-line quotes bytes internal constant TEMPLATE = 'data:text/plain,{"name":"Mandala 0x0000000000000000000000000000000000000000","description":"A Unique Mandala","image":"data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' shape-rendering=\'crispEdges\' width=\'512\' height=\'512\'><g transform=\'scale(64)\'><image width=\'8\' height=\'8\' style=\'image-rendering: pixelated;\' href=\'data:image/gif;base64,R0lGODdhEwATAMQAAAAAAPb+Y/7EJfN3NNARQUUKLG0bMsR1SujKqW7wQwe/dQBcmQeEqjDR0UgXo4A0vrlq2AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkKAAAALAAAAAATABMAAAdNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABNgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA6gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGBADs=\'/></g></svg>"}'; uint256 internal constant IMAGE_DATA_POS = 521; uint256 internal constant ADDRESS_NAME_POS = 74; uint256 internal constant WIDTH = 19; uint256 internal constant HEIGHT = 19; uint256 internal constant ROW_PER_BLOCK = 4; bytes32 constant internal xs = 0x8934893467893456789456789567896789789899000000000000000000000000; bytes32 constant internal ys = 0x0011112222223333333444444555556666777889000000000000000000000000; event Minted(uint256 indexed id, uint256 indexed pricePaid); event Burned(uint256 indexed id, uint256 indexed priceReceived); event CreatorshipTransferred(address indexed previousCreator, address indexed newCreator); uint256 public immutable linearCoefficient; uint256 public immutable initialPrice; uint256 public immutable creatorCutPer10000th; address payable public creator; constructor(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) { require(_creatorCutPer10000th < 2000, "CREATOR_CUT_ROO_HIGHT"); initialPrice = _initialPrice; creatorCutPer10000th = _creatorCutPer10000th; linearCoefficient = _linearCoefficient; postUpgrade(_creator, _initialPrice, _creatorCutPer10000th, _linearCoefficient); } // solhint-disable-next-line no-unused-vars function postUpgrade(address payable _creator, uint256 _initialPrice, uint256 _creatorCutPer10000th, uint256 _linearCoefficient) public proxied { // immutables are set in the constructor: // initialPrice = _initialPrice; // creatorCutPer10000th = _creatorCutPer10000th; // linearCoefficient = _linearCoefficient; creator = _creator; emit CreatorshipTransferred(address(0), creator); } function transferCreatorship(address payable newCreatorAddress) external { address oldCreator = creator; require(oldCreator == msg.sender, "NOT_AUTHORIZED"); creator = newCreatorAddress; emit CreatorshipTransferred(oldCreator, newCreatorAddress); } /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure override returns (string memory) { return "Mandala Tokens"; } /// @notice An abbreviated name for NFTs in this contract function symbol() external pure override returns (string memory) { return "MANDALA"; } function tokenURI(uint256 id) public view virtual override returns (string memory) { address owner = _ownerOf(id); require(owner != address(0), "NOT_EXISTS"); return _tokenURI(id); } /// @notice Check if the contract supports an interface. /// 0x01ffc9a7 is ERC165. /// 0x80ac58cd is ERC721 /// 0x5b5e139f is for ERC721 metadata /// 0x780e9d63 is for ERC721 enumerable /// @param id The id of the interface. /// @return Whether the interface is supported. function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) { return ERC721Base.supportsInterface(id) || id == 0x5b5e139f; } struct TokenData { uint256 id; string tokenURI; } function getTokenDataOfOwner( address owner, uint256 start, uint256 num ) external view returns (TokenData[] memory tokens) { EnumerableSet.UintSet storage allTokens = _holderTokens[owner]; uint256 balance = allTokens.length(); require(balance >= start + num, "TOO_MANY_TOKEN_REQUESTED"); tokens = new TokenData[](num); uint256 i = 0; while (i < num) { uint256 id = allTokens.at(start + i); tokens[i] = TokenData(id, _tokenURI(id)); i++; } } function mint(address to, bytes memory signature) external payable returns (uint256) { uint256 mintPrice = _curve(_supply); require(msg.value >= mintPrice, "NOT_ENOUGH_ETH"); // -------------------------- MINTING --------------------------------------------------------- bytes32 hashedData = keccak256(abi.encodePacked("Mandala", to)); address signer = hashedData.toEthSignedMessageHash().recover(signature); _mint(uint256(signer), to); // -------------------------- MINTING --------------------------------------------------------- uint256 forCreator = mintPrice - _forReserve(mintPrice); // responsibility of the creator to ensure it can receive the fund bool success = true; if (forCreator > 0) { // solhint-disable-next-line check-send-result success = creator.send(forCreator); } if(!success || msg.value > mintPrice) { msg.sender.transfer(msg.value - mintPrice + (!success ? forCreator : 0)); } emit Minted(uint256(signer), mintPrice); return uint256(signer); } function burn(uint256 id) external { uint256 burnPrice = _forReserve(_curve(_supply - 1)); _burn(id); msg.sender.transfer(burnPrice); emit Burned(id, burnPrice); } function currentPrice() external view returns (uint256) { return _curve(_supply); } function _curve(uint256 supply) internal view returns (uint256) { return initialPrice + supply * linearCoefficient; } function _forReserve(uint256 mintPrice) internal view returns (uint256) { return mintPrice * (10000-creatorCutPer10000th) / 10000; } // solhint-disable-next-line code-complexity function _tokenURI(uint256 id) internal pure returns (string memory) { bytes memory metadata = TEMPLATE; writeUintAsHex(metadata, ADDRESS_NAME_POS, id); for (uint256 i = 0; i < 40; i++) { uint8 value = uint8((id >> (40-(i+1))*4) % 16); if (value == 0) { value = 16; // use black as oposed to transparent } uint256 x = extract(xs, i); uint256 y = extract(ys, i); setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + x + (y /ROW_PER_BLOCK) * 2 + 1, value); if (x != y) { setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + y + (x /ROW_PER_BLOCK) * 2 + 1, value); if (y != HEIGHT / 2) { setCharacter(metadata, IMAGE_DATA_POS, x*WIDTH + (WIDTH -y -1) + (x /ROW_PER_BLOCK) * 2 + 1, value); // x mirror } if (x != WIDTH / 2) { setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + y + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror } if (x != WIDTH / 2 && y != HEIGHT / 2) { setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-x-1)*WIDTH + (WIDTH-y-1) + ((HEIGHT-x-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror } } if (x != WIDTH / 2) { setCharacter(metadata, IMAGE_DATA_POS, y*WIDTH + (WIDTH -x -1) + (y /ROW_PER_BLOCK) * 2 + 1, value); // x mirror } if (y != HEIGHT / 2) { setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + x + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // y mirror } if (x != WIDTH / 2 && y != HEIGHT / 2) { setCharacter(metadata, IMAGE_DATA_POS, (HEIGHT-y-1)*WIDTH + (WIDTH-x-1) + ((HEIGHT-y-1) /ROW_PER_BLOCK) * 2 + 1, value); // x,y mirror } } return string(metadata); } function setCharacter(bytes memory metadata, uint256 base, uint256 pos, uint8 value) internal pure { uint256 base64Slot = base + (pos * 8) / 6; uint8 bit = uint8((pos * 8) % 6); uint8 existingValue = base64ToUint8(metadata[base64Slot]); if (bit == 0) { metadata[base64Slot] = uint8ToBase64(value >> 2); uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]); metadata[base64Slot + 1] = uint8ToBase64(((value % 4) << 4) | (0x0F & extraValue)); } else if (bit == 2) { metadata[base64Slot] = uint8ToBase64((value >> 4) | (0x30 & existingValue)); uint8 extraValue = base64ToUint8(metadata[base64Slot + 1]); metadata[base64Slot + 1] = uint8ToBase64(((value % 16) << 2) | (0x03 & extraValue)); } else { // bit == 4) // metadata[base64Slot] = uint8ToBase64((value >> 6) | (0x3C & existingValue)); // skip as value are never as big metadata[base64Slot + 1] = uint8ToBase64(value % 64); } } function extract(bytes32 arr, uint256 i) internal pure returns (uint256) { return (uint256(arr) >> (256 - (i+1) * 4)) % 16; } bytes32 constant internal base64Alphabet_1 = 0x4142434445464748494A4B4C4D4E4F505152535455565758595A616263646566; bytes32 constant internal base64Alphabet_2 = 0x6768696A6B6C6D6E6F707172737475767778797A303132333435363738392B2F; function base64ToUint8(bytes1 s) internal pure returns (uint8 v) { if (uint8(s) == 0x2B) { return 62; } if (uint8(s) == 0x2F) { return 63; } if (uint8(s) >= 0x30 && uint8(s) <= 0x39) { return uint8(s) - 0x30 + 52; } if (uint8(s) >= 0x41 && uint8(s) <= 0x5A) { return uint8(s) - 0x41; } if (uint8(s) >= 0x5A && uint8(s) <= 0x7A) { return uint8(s) - 0x5A + 26; } return 0; } function uint8ToBase64(uint24 v) internal pure returns (bytes1 s) { if (v >= 32) { return base64Alphabet_2[v - 32]; } return base64Alphabet_1[v]; } bytes constant internal hexAlphabet = "0123456789abcdef"; function writeUintAsHex(bytes memory data, uint256 endPos, uint256 num) internal pure { while (num != 0) { data[endPos--] = bytes1(hexAlphabet[num % 16]); num /= 16; } } }
Check if the contract supports an interface. 0x01ffc9a7 is ERC165. 0x80ac58cd is ERC721 0x5b5e139f is for ERC721 metadata 0x780e9d63 is for ERC721 enumerable id The id of the interface. return Whether the interface is supported.
function supportsInterface(bytes4 id) public pure virtual override(ERC721Base, IERC165) returns (bool) { return ERC721Base.supportsInterface(id) || id == 0x5b5e139f; }
14,879,215
pragma solidity ^0.6.4; pragma experimental ABIEncoderV2; import "../governance/Governed.sol"; import "../curation/ICuration.sol"; import "../token/IGraphToken.sol"; import "../bancor/BancorFormula.sol"; import "./erc1056/IEthereumDIDRegistry.sol"; /** * @title GNS * @dev The Graph Name System contract provides a decentralized namings system for subgraphs * used in the scope of the Graph Network. It translates subgraph names into subgraph versions. * Each version is associated with a Subgraph Deployment. The contract no knowledge of human * readable names. All human readable names emitted in events. */ contract GNS is Governed, BancorFormula { // -- State -- struct NameCurationPool { uint256 vSignal; // The token of the subgraph deployment bonding curve uint256 nSignal; // The token of the name curation bonding curve mapping(address => uint256) curatorNSignal; bytes32 subgraphDeploymentID; uint32 reserveRatio; bool disabled; uint256 withdrawableGRT; } // Equates to Connector weight on bancor formula to be CW = 1 uint32 private constant defaultReserveRatio = 1000000; // Amount of nSignal you get with your minimum vSignal stake uint256 private constant VSIGNAL_PER_MINIMUM_NSIGNAL = 1 ether; // Minimum amount of vSignal that must be staked to start the curve // Set to 10**18, as vSignal has 18 decimals uint256 public minimumVSignalStake = 10**18; // graphAccountID => subgraphNumber => subgraphDeploymentID // subgraphNumber = A number associated to a graph accounts deployed subgraph. This // is used to point to a subgraphID (graphAccountID + subgraphNumber) mapping(address => mapping(uint256 => bytes32)) public subgraphs; // graphAccountID => subgraph deployment counter mapping(address => uint256) public graphAccountSubgraphNumbers; // graphAccountID => subgraphNumber => NameCurationPool mapping(address => mapping(uint256 => NameCurationPool)) public nameSignals; // ERC-1056 contract reference IEthereumDIDRegistry public erc1056Registry; // Curation contract reference ICuration public curation; // Token used for staking IGraphToken public token; // -- Events -- /** * @dev Emitted when graph account sets their default name */ event SetDefaultName( address graphAccount, uint256 nameSystem, // only ENS for now bytes32 nameIdentifier, string name ); /** * @dev Emitted when graph account sets a subgraphs metadata on IPFS */ event SubgraphMetadataUpdated( address graphAccount, uint256 subgraphNumber, bytes32 subgraphMetadata ); /** * @dev Emitted when a `graph account` publishes a `subgraph` with a `version`. * Every time this event is emitted, indicates a new version has been created. * The event also emits a `metadataHash` with subgraph details and version details. */ event SubgraphPublished( address graphAccount, uint256 subgraphNumber, bytes32 subgraphDeploymentID, bytes32 versionMetadata ); /** * @dev Emitted when a graph account deprecated one of their subgraphs */ event SubgraphDeprecated(address graphAccount, uint256 subgraphNumber); /** * @dev Emitted when a graphAccount creates an nSignal bonding curve that * points to a subgraph deployment */ event NameSignalEnabled( address graphAccount, uint256 subgraphNumber, bytes32 subgraphDeploymentID, uint32 reserveRatio ); /** * @dev Emitted when a name curator deposits their vSignal into an nSignal curve to mint nSignal */ event NSignalMinted( address graphAccount, uint256 subgraphNumber, address nameCurator, uint256 nSignalCreated, uint256 vSignalCreated, uint256 tokensDeposited ); /** * @dev Emitted when a name curator burns their nSignal, which in turn burns * the vSignal, and receives GRT */ event NSignalBurned( address graphAccount, uint256 subgraphNumber, address nameCurator, uint256 nSignalBurnt, uint256 vSignalBurnt, uint256 tokensReceived ); /** * @dev Emitted when a graph account upgrades their nSignal curve to point to a new * subgraph deployment, burning all the old vSignal and depositing the GRT into the * new vSignal curve, creating new nSignal */ event NameSignalUpgrade( address graphAccount, uint256 subgraphNumber, uint256 newVSignalCreated, uint256 tokensSignalled, bytes32 subgraphDeploymentID ); /** * @dev Emitted when an nSignal curve has been permanently disabled */ event NameSignalDisabled(address graphAccount, uint256 subgraphNumber, uint256 withdrawableGRT); /** * @dev Emitted when a nameCurator withdraws their GRT from a deprecated name signal pool */ event GRTWithdrawn( address graphAccount, uint256 subgraphNumber, address nameCurator, uint256 nSignalBurnt, uint256 withdrawnGRT ); /** @dev Modifier that allows a function to be called by owner of a graph account @param _graphAccount Address of the graph account */ modifier onlyGraphAccountOwner(address _graphAccount) { address graphAccountOwner = erc1056Registry.identityOwner(_graphAccount); require(graphAccountOwner == msg.sender, "GNS: Only graph account owner can call"); _; } /** * @dev Contract Constructor. * @param _didRegistry Address of the Ethereum DID registry * @param _curation Address of the Curation contract * @param _token Address of the Graph Token contract */ constructor( address _didRegistry, address _curation, address _token ) public { Governed._initialize(msg.sender); erc1056Registry = IEthereumDIDRegistry(_didRegistry); curation = ICuration(_curation); token = IGraphToken(_token); token.approve(_curation, uint256(-1)); } /** * @dev Set the minimum vSignal to be staked to create nSignal * @notice Update the minimum vSignal amount to `_minimumVSignalStake` * @param _minimumVSignalStake Minimum amount of vSignal required */ function setMinimumVsignal(uint256 _minimumVSignalStake) external onlyGovernor { require(_minimumVSignalStake > 0, "Minimum vSignal cannot be 0"); minimumVSignalStake = _minimumVSignalStake; emit ParameterUpdated("minimumVSignalStake"); } /** * @dev Allows a graph account to set a default name * @param _graphAccount Account that is setting their name * @param _nameSystem Name system account already has ownership of a name in * @param _nameIdentifier The unique identifier that is used to identify the name in the system * @param _name The name being set as default */ function setDefaultName( address _graphAccount, uint8 _nameSystem, bytes32 _nameIdentifier, string calldata _name ) external onlyGraphAccountOwner(_graphAccount) { emit SetDefaultName(_graphAccount, _nameSystem, _nameIdentifier, _name); } /** * @dev Allows a graph account update the metadata of a subgraph they have published * @param _graphAccount Account that owns the subgraph * @param _subgraphNumber Subgraph number * @param _subgraphMetadata IPFS hash for the subgraph metadata */ function updateSubgraphMetadata( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphMetadata ) public onlyGraphAccountOwner(_graphAccount) { emit SubgraphMetadataUpdated(_graphAccount, _subgraphNumber, _subgraphMetadata); } /** * @dev Allows a graph account to publish a new subgraph, which means a new subgraph number * will be used. * @param _graphAccount Account that is publishing the subgraph * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata * @param _subgraphMetadata IPFS hash for the subgraph metadata */ function publishNewSubgraph( address _graphAccount, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata, bytes32 _subgraphMetadata ) external onlyGraphAccountOwner(_graphAccount) { uint256 subgraphNumber = graphAccountSubgraphNumbers[_graphAccount]; _publishVersion(_graphAccount, subgraphNumber, _subgraphDeploymentID, _versionMetadata); graphAccountSubgraphNumbers[_graphAccount]++; updateSubgraphMetadata(_graphAccount, subgraphNumber, _subgraphMetadata); _enableNameSignal(_graphAccount, subgraphNumber); } /** * @dev Allows a graph account to publish a new version of their subgraph. * Version is derived from the occurance of SubgraphPublished being emitted. * The first time SubgraphPublished is called would be Version 0 * @param _graphAccount Account that is publishing the subgraph * @param _subgraphNumber Subgraph number for the account * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata */ function publishNewVersion( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata ) external onlyGraphAccountOwner(_graphAccount) { require( isPublished(_graphAccount, _subgraphNumber), "GNS: Cannot update version if not published, or has been deprecated" ); bytes32 oldSubgraphDeploymentID = subgraphs[_graphAccount][_subgraphNumber]; require( _subgraphDeploymentID != oldSubgraphDeploymentID, "GNS: Cannot publish a new version with the same subgraph deployment ID" ); _publishVersion(_graphAccount, _subgraphNumber, _subgraphDeploymentID, _versionMetadata); _upgradeNameSignal(_graphAccount, _subgraphNumber, _subgraphDeploymentID); } /** * @dev Private function used by both external publishing functions * @param _graphAccount Account that is publishing the subgraph * @param _subgraphNumber Subgraph number for the account * @param _subgraphDeploymentID Subgraph deployment ID of the version, linked to the name * @param _versionMetadata IPFS hash for the subgraph version metadata */ function _publishVersion( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID, bytes32 _versionMetadata ) private { require(_subgraphDeploymentID != 0, "GNS: Cannot set deploymentID to 0 in publish"); // Stores a subgraph deployment ID, which indicates a version has been created subgraphs[_graphAccount][_subgraphNumber] = _subgraphDeploymentID; // Emit version and name data emit SubgraphPublished( _graphAccount, _subgraphNumber, _subgraphDeploymentID, _versionMetadata ); } /** * @dev Deprecate a subgraph. Can only be done by the graph account owner. * @param _graphAccount Account that is publishing the subgraph * @param _subgraphNumber Subgraph number for the account */ function deprecateSubgraph(address _graphAccount, uint256 _subgraphNumber) external onlyGraphAccountOwner(_graphAccount) { require( isPublished(_graphAccount, _subgraphNumber), "GNS: Cannot deprecate a subgraph which does not exist" ); bytes32 subgraphDeploymentID = subgraphs[_graphAccount][_subgraphNumber]; delete subgraphs[_graphAccount][_subgraphNumber]; emit SubgraphDeprecated(_graphAccount, _subgraphNumber); _disableNameSignal(_graphAccount, _subgraphNumber, subgraphDeploymentID); } /** * @dev Enable name signal on a graph accounts numbered subgraph, which points to a subgraph * deployment * @param _graphAccount Graph account enabling name signal * @param _subgraphNumber Subgraph number being used */ function _enableNameSignal(address _graphAccount, uint256 _subgraphNumber) private { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; bytes32 subgraphDeploymentID = subgraphs[_graphAccount][_subgraphNumber]; namePool.reserveRatio = defaultReserveRatio; namePool.subgraphDeploymentID = subgraphDeploymentID; emit NameSignalEnabled( _graphAccount, _subgraphNumber, subgraphDeploymentID, defaultReserveRatio ); } /** * @dev Update a name signal on a graph accounts numbered subgraph * @param _graphAccount Graph account updating name signal * @param _subgraphNumber Subgraph number being used * @param _newSubgraphDeploymentID Deployment ID being upgraded to */ function _upgradeNameSignal( address _graphAccount, uint256 _subgraphNumber, bytes32 _newSubgraphDeploymentID ) private { // This is to prevent the owner from front running their name curators signal by posting // their own signal ahead, bringing the name curators in, and dumping on them require( !curation.isCurated(_newSubgraphDeploymentID), "GNS: Owner cannot point to a subgraphID that has been pre-curated" ); NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require( namePool.nSignal > 0, "GNS: There must be nSignal on this subgraph for curve math to work" ); require(namePool.disabled == false, "GNS: Cannot be disabled"); uint256 vSignalOld = nSignalToVSignal(_graphAccount, _subgraphNumber, namePool.nSignal); (uint256 tokens, uint256 withdrawalFees) = _burnVSignal( _graphAccount, namePool.subgraphDeploymentID, vSignalOld ); namePool.vSignal = namePool.vSignal.sub(vSignalOld); // Update name signals deployment ID to match the subgraphs deployment ID namePool.subgraphDeploymentID = _newSubgraphDeploymentID; // nSignal stays constant, but vSignal can change here uint256 vSignalNew = curation.mint( namePool.subgraphDeploymentID, (tokens + withdrawalFees) ); namePool.vSignal = vSignalNew; emit NameSignalUpgrade( _graphAccount, _subgraphNumber, vSignalNew, tokens + withdrawalFees, _newSubgraphDeploymentID ); } /** * @dev Allow a name curator to mint some nSignal by depositing GRT * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number * @param _tokens The amount of tokens the nameCurator wants to deposit */ function mintNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokens ) external { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require(namePool.disabled == false, "GNS: Cannot be disabled"); require( namePool.subgraphDeploymentID != 0, "GNS: Must deposit on a name signal that exists" ); _mintNSignal(_graphAccount, _subgraphNumber, _tokens); } /** * @dev Allow a nameCurator to burn some of their nSignal and get GRT in return * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignal The amount of nSignal the nameCurator wants to burn */ function burnNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal ) external { address nameCurator = msg.sender; NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 curatorNSignal = namePool.curatorNSignal[nameCurator]; require(namePool.disabled == false, "GNS: Cannot be disabled"); require( _nSignal <= curatorNSignal, "GNS: Curator cannot withdraw more nSignal than they have" ); _burnNSignal(_graphAccount, _subgraphNumber, _nSignal); } /** * @dev Owner disables the subgraph. This means the subgraph-number combination can no longer * be used for name signal. The nSignal curve is destroyed, the vSignal is burned, and the GNS * contract holds the GRT from burning the vSignal, which all curators can withdraw manually. * @param _graphAccount Account that is deprecating their name curation * @param _subgraphNumber Subgraph number * @param _subgraphDeploymentID Subgraph deployment ID of the deprecating subgraph */ function _disableNameSignal( address _graphAccount, uint256 _subgraphNumber, bytes32 _subgraphDeploymentID ) private { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = namePool.vSignal; namePool.vSignal = 0; // If no nSignal, then no need to burn vSignal if (namePool.nSignal != 0) { (uint256 tokens, uint256 withdrawalFees) = curation.burn( _subgraphDeploymentID, vSignal ); // Get the owner of the Name to reimburse the withdrawal fee require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); namePool.withdrawableGRT = tokens + withdrawalFees; } // Set the NameCurationPool fields to make it disabled namePool.disabled = true; emit NameSignalDisabled(_graphAccount, _subgraphNumber, namePool.withdrawableGRT); } /** * @dev When the subgraph curve is disabled, all nameCurators can call this function and * withdraw the GRT they are entitled for their original deposit of vSignal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators */ function withdraw(address _graphAccount, uint256 _subgraphNumber) external { NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; require(namePool.disabled == true, "GNS: Name bonding curve must be disabled first"); require(namePool.withdrawableGRT > 0, "GNS: No more GRT to withdraw"); uint256 curatorNSignal = namePool.curatorNSignal[msg.sender]; require(curatorNSignal > 0, "GNS: Curator must have some nSignal to withdraw GRT"); uint256 tokens = curatorNSignal.mul(namePool.withdrawableGRT).div(namePool.nSignal); namePool.curatorNSignal[msg.sender] = 0; namePool.nSignal = namePool.nSignal.sub(curatorNSignal); namePool.withdrawableGRT = namePool.withdrawableGRT.sub(tokens); require( token.transfer(msg.sender, tokens), "GNS: Error withdrawing tokens for nameCurator" ); emit GRTWithdrawn(_graphAccount, _subgraphNumber, msg.sender, curatorNSignal, tokens); } /** * @dev Calculations for buying name signal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _tokens GRT being deposited into vSignal to create nSignal * @return vSignal and tokens */ function _mintNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokens ) private returns (uint256, uint256) { require( token.transferFrom(msg.sender, address(this), _tokens), "GNS: Cannot transfer tokens to mint n signal" ); NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = curation.mint(namePool.subgraphDeploymentID, _tokens); uint256 nSignal = vSignalToNSignal(_graphAccount, _subgraphNumber, vSignal); namePool.vSignal = namePool.vSignal.add(vSignal); namePool.nSignal = namePool.nSignal.add(nSignal); namePool.curatorNSignal[msg.sender] = namePool.curatorNSignal[msg.sender].add(nSignal); emit NSignalMinted(_graphAccount, _subgraphNumber, msg.sender, nSignal, vSignal, _tokens); return (vSignal, nSignal); } /** * @dev Calculations for burning name signal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignal nSignal being burnt to receive vSignal to be burnt into GRT * @return vSignal and nSignal */ function _burnNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal ) private returns (uint256, uint256) { address nameCurator = msg.sender; NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignal); (uint256 tokens, ) = curation.burn(namePool.subgraphDeploymentID, vSignal); namePool.vSignal = namePool.vSignal.sub(vSignal); namePool.nSignal = namePool.nSignal.sub(_nSignal); namePool.curatorNSignal[msg.sender] = namePool.curatorNSignal[msg.sender].sub(_nSignal); // Return the tokens to the nameCurator require(token.transfer(nameCurator, tokens), "GNS: Error sending nameCurators tokens"); emit NSignalBurned(_graphAccount, _subgraphNumber, msg.sender, _nSignal, vSignal, tokens); return (vSignal, tokens); } /** * @dev Calculations burning vSignal from disabled or upgrade, while keeping n signal constant. * Takes the withdrawal fee from the name owner so they cannot grief all the name curators * @param _graphAccount Subgraph owner * @param _subgraphDeploymentID Subgraph deployment to burn all vSignal from * @param _vSignal vSignal being burnt * @return Tokens returned to the gns contract, and withdrawal fees the owner transferred to the gns */ function _burnVSignal( address _graphAccount, bytes32 _subgraphDeploymentID, uint256 _vSignal ) private returns (uint256, uint256) { (uint256 tokens, uint256 withdrawalFees) = curation.burn(_subgraphDeploymentID, _vSignal); require( token.transferFrom(_graphAccount, address(this), withdrawalFees), "GNS: Error reimbursing withdrawal fees" ); return (tokens, withdrawalFees); } /** * @dev Calculate nSignal to be returned for an amount of tokens * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _tokens Tokens being exchanged for nSignal * @return Amount of vSignal and nSignal that can be returned */ function tokensToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _tokens ) public view returns (uint256, uint256) { NameCurationPool memory namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = curation.tokensToSignal(namePool.subgraphDeploymentID, _tokens); uint256 nSignal = vSignalToNSignal(_graphAccount, _subgraphNumber, vSignal); return (vSignal, nSignal); } /** * @dev Calculate n signal to be returned for an amount of tokens * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignal nSignal being exchanged for tokens * @return Amount of vSignal and tokens that can be returned */ function nSignalToTokens( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal ) public view returns ( uint256, uint256, uint256 ) { NameCurationPool memory namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = nSignalToVSignal(_graphAccount, _subgraphNumber, _nSignal); (uint256 tokens, uint256 withdrawalFees) = curation.signalToTokens( namePool.subgraphDeploymentID, vSignal ); return (vSignal, tokens, withdrawalFees); } /** * @dev Calculate nSignal to be returned for an amount of vSignal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _vSignal being used for calculation * @return Amount of nSignal that can be bought */ function vSignalToNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _vSignal ) public view returns (uint256) { NameCurationPool memory namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 vSignal = _vSignal; uint256 nSignalInit = 0; uint32 reserveRatio = namePool.reserveRatio; // Handle initialization of bonding curve if (namePool.vSignal == 0) { namePool.vSignal = minimumVSignalStake; vSignal = vSignal.sub(namePool.vSignal); namePool.nSignal = VSIGNAL_PER_MINIMUM_NSIGNAL; nSignalInit = namePool.nSignal; reserveRatio = defaultReserveRatio; } return calculatePurchaseReturn( namePool.nSignal, namePool.vSignal, reserveRatio, vSignal // deposit the vSignal into the nSignal bonding curve ) + nSignalInit; } /** * @dev Calculate vSignal to be returned for an amount of nSignal * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _nSignal nSignal being exchanged for vSignal * @return Amount of vSignal that can be returned */ function nSignalToVSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal ) public view returns (uint256) { NameCurationPool memory namePool = nameSignals[_graphAccount][_subgraphNumber]; return calculateSaleReturn( namePool.nSignal, namePool.vSignal, namePool.reserveRatio, _nSignal ); } /** * @dev Get the amount of name signal a curator has on a name pool. * @param _graphAccount Subgraph owner * @param _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators * @param _curator Curator to look up to see n signal balance * @return Amount of name signal owned by a curator for the name pool */ function getCuratorNSignal( address _graphAccount, uint256 _subgraphNumber, address _curator ) public view returns (uint256) { return nameSignals[_graphAccount][_subgraphNumber].curatorNSignal[_curator]; } /** * @dev Return whether a subgraph name is published. * @param _graphAccount Account being checked * @param _subgraphNumber Subgraph number being checked for publishing * @return Return true if subgraph is currently published */ function isPublished(address _graphAccount, uint256 _subgraphNumber) public view returns (bool) { return subgraphs[_graphAccount][_subgraphNumber] != 0; } }
Allow a nameCurator to burn some of their nSignal and get GRT in return _graphAccount Subgraph owner _subgraphNumber Subgraph owners subgraph number which was curated on by nameCurators _nSignal The amount of nSignal the nameCurator wants to burn/
function burnNSignal( address _graphAccount, uint256 _subgraphNumber, uint256 _nSignal ) external { address nameCurator = msg.sender; NameCurationPool storage namePool = nameSignals[_graphAccount][_subgraphNumber]; uint256 curatorNSignal = namePool.curatorNSignal[nameCurator]; require(namePool.disabled == false, "GNS: Cannot be disabled"); require( _nSignal <= curatorNSignal, "GNS: Curator cannot withdraw more nSignal than they have" ); _burnNSignal(_graphAccount, _subgraphNumber, _nSignal); }
13,095,546
/** *Submitted for verification at Etherscan.io on 2021-12-14 */ /** *Submitted for verification at Etherscan.io on 2021-10-07 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } 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); } } 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); } } } } 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); } 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); } 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; } } 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; } 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); } 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); } 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; } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ /** * @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); } } 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; string public _baseURI; /** * @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 base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, 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; } /** * @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 {} } 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(); } } pragma solidity ^0.8.0; contract MysticAliens is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; uint public constant _TOTALSUPPLY =2022; uint public maxPerTx =5; uint256 public price = 0.15 ether; bool public isPaused = true; uint private tokenId=1; constructor(string memory baseURI) ERC721("MysticAliens", "MA") { setBaseURI(baseURI); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setPrice(uint256 _newPrice) public onlyOwner() { price = _newPrice; } function setMaxxQtPerTx(uint256 _quantity) public onlyOwner { maxPerTx=_quantity; } modifier isSaleOpen{ require(totalSupply() < _TOTALSUPPLY, "Sale end"); _; } function flipPauseStatus() public onlyOwner { isPaused = !isPaused; } function getPrice(uint256 _quantity) public view returns (uint256) { return _quantity*price ; } function mint(uint chosenAmount) public payable isSaleOpen{ require(isPaused == false, "Sale is not active at the moment"); require(totalSupply()+chosenAmount<=_TOTALSUPPLY,"Quantity must be lesser then remaining NFTs"); require(chosenAmount > 0, "Number of NFTs can not be less than or equal to 0"); require(chosenAmount <= maxPerTx,"Chosen Amount exceeds MaxQuantity allowed per transaction"); require(chosenAmount+balanceOf(msg.sender)<=10, "Maximum of 10 NFTs can be owned by one person"); require(price.mul(chosenAmount) == msg.value,"Sent ether value is not correct"); for (uint i = 0; i < chosenAmount; i++) { _safeMint(msg.sender, totalsupply()); tokenId++; } } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory base = baseURI(); return bytes(base).length > 0 ? string(abi.encodePacked(base, tokenId.toString(), ".json")) : ""; } function tokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 count = balanceOf(_owner); uint256[] memory result = new uint256[](count); for (uint256 index = 0; index < count; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function contractURI() public view returns (string memory) { string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Mystic Aliens", "description": "For decades, humans have researched and wondered about life beyond Earth. The search is finally over, 2022 Mystic Aliens have landed and they brought a spaceship full of otherworldly treasures - you too can reap the rewards of the Mystic Aliens one of a kind staking + DAO Protocol. APY that is out of this world, literally. Programmatically and randomly generated on the Ethereum Blockchain. Each Alien is unique, made from a combination of more than 50 attributes drawn by hand. A Mystic Alien is both a NFT collectible and a key to enter the spaceship and a lot more.", "seller_fee_basis_points": 1000, "fee_recipient": "0x2C0593Bbd2182C7818ab624FEC0d35EDad917C47"}')))); json = string(abi.encodePacked('data:application/json;base64,', json)); return json; } function totalsupply() private view returns (uint) { return tokenId; } } library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } }
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.adocusing-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); _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); _addTokenToOwnerEnumeration(to, tokenId); } }
1,274,423
/** * Rupiah Token Smart Contract * Copyright (C) 2019 PT. Rupiah Token Indonesia <https://www.rupiahtoken.com/>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * This file incorporates work covered byt the following copyright and * permission notice: * * OpenZeppelin <https://github.com/OpenZeppelin/openzeppelin-solidity/> * Copyright (c) 2016 Smart Contract Solutions, Inc. * Modified for Rupiah Token by FengkieJ 2019. * * centre-tokens <https://github.com/centrehq/centre-tokens> * Copyright CENTRE SECZ 2018. * Modified for Rupiah Token by FengkieJ 2019. * * ZeppelinOS (zos) <https://github.com/zeppelinos/zos> * Copyright (c) 2018 ZeppelinOS Global Limited. * * The MIT License (MIT) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to * do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity 0.4.25; import "./IERC20.sol"; import "../math/SafeMath.sol"; import "../governance/Blacklistable.sol"; import "../lifecycle/Pausable.sol"; import "../ownership/Ownable.sol"; import "../zos/Initializable.sol"; /** * @title ERC20RupiahToken * @dev ERC20 compliant fiat token that is backed by Indonesian Rupiah 1:1 */ contract ERC20RupiahToken is IERC20, Blacklistable, Initializable { using SafeMath for uint256; string internal _name; string internal _symbol; string internal _currency; uint8 internal _decimals; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; uint256 internal _totalSupply; /** * @dev Initialize the smart contract to work with ZeppelinOS, can only be called once. * @param name describes the name of the token. * @param symbol describes the symbol of the token. * @param currency describes the currency of the token. * @param decimals describes the number of decimals of the token. */ function initialize(string name, string symbol, string currency, uint8 decimals) initializer public { owner = msg.sender; _name = name; _symbol = symbol; _currency = currency; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the currency of the token. */ function currency() public view returns (string memory) { return _currency; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * @return the total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(to) returns (bool) { require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(from) notBlacklisted(to) returns (bool) { require(to != address(0)); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused notBlacklisted(msg.sender) notBlacklisted(spender) returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function mint(address account, uint256 value) public whenNotPaused notBlacklisted(account) onlyOwner { require(account != address(0)); value = value.mul(10**_decimals); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Function that burns an amount of the token. * @param value The amount that will be burnt. */ function burn(uint256 value) public whenNotPaused onlyOwner { value = value.mul(10**_decimals); _totalSupply = _totalSupply.sub(value); _balances[msg.sender] = _balances[msg.sender].sub(value); emit Transfer(msg.sender, address(0), value); } /** * @dev Function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function burnFrom(address account, uint256 value) public whenNotPaused notBlacklisted(account) onlyOwner { require(account != address(0)); value = value.mul(10**_decimals); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } }
Function that mints an amount of the token and assigns it to an account. This encapsulates the modification of balances such that the proper events are emitted. account The account that will receive the created tokens. value The amount that will be created./
function mint(address account, uint256 value) public whenNotPaused notBlacklisted(account) onlyOwner { require(account != address(0)); value = value.mul(10**_decimals); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); }
6,415,279
./full_match/43114/0xe9EFbDC0c060B87ea94fEeEA1ECB23207AF8d9F1/sources/_AttackWolfStake.sol
RandomContract = IRandom(0x47E06280Ff1D2236F0Dd4D3Db99e74Dd14a88295); BuyContract = IBuy(0x79c6AD13b3deFE0A706557Df3540de15c0adD0A3); WBNB = 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c; PATH_TOKEN_BNB = [0x69fb6653762a951075123c408e905B63691367fC,0x55d398326f99059fF775485246999027B3197955,0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c]; PATH_BNB_TOKEN = [0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c,0xdeFe17E96f89c359AA2325a196f07ACe730CE329]; SwapContract = ISwap(0x10ED43C718714eb63d5aA57B78B54704E256024E);NftContract.setApprovalForAll(address(this),true);
function initAdmin() public{ require(AProxy(address(this)).admin() == msg.sender,"not proxy admin"); admin = msg.sender; admins[admin] = true; NftContract = IERC721(0x79c6AD13b3deFE0A706557Df3540de15c0adD0A3); TokenContract = IERC20(0xD17D39460B0b8B57a68cA8b69aaB6f611740Abfc); MAX_COUNT = 100; StakeContract = IStake(0xd9B6F4d6E04532e7aC1e196b81Ee959e2De5E987); NftContract.setApprovalForAll(address(StakeContract),true); TokenContract.approve(address(NftContract),uint256(-1)); }
4,507,102
./full_match/1/0xF1D6C34540013D652069f6dDC65F6F8095aB2a73/sources/contracts/Robottoz.sol
devMint for collabs, community, treasury, etc
function devMint(uint256 _quantity) external onlyOwner { require(_totalMinted() + _quantity <= maxRobots, "Max robots reached"); _safeMint(msg.sender, _quantity); if (_totalMinted() >= freeMax) { freeSale = false; } }
16,560,017
./full_match/41/0xC450EdCeD6b99Ac4b2B0D3A62a67f119Af631629/sources/project_/contracts/libraries/WhaleLibrary.sol
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, 'WhaleLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'WhaleLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(10000); uint denominator = reserveOut.sub(amountOut).mul(9975); amountIn = (numerator / denominator).add(1); }
16,374,246
./full_match/43114/0xEB76152131728478fe7E38ab7169aBaB283861D3/sources/TraderJoeCompoundingStrategyToken.sol
Performs an emergency withdrawal from the MasterChef pool
function _emergencyWithdraw() internal { MasterChefJoe(masterChef).emergencyWithdraw(pid); }
4,592,888
./partial_match/42/0x786fdD0A822490D62Db2bA65EEBa8cd684968FF7/sources/BatterseaScriptsV1.sol
Locks collateral into the vault in the BalanceSheet contract and draws debt via the FyToken contract. balanceSheet The address of the BalanceSheet contract. fyToken The address of the FyToken contract. collateralAmount The amount of collateral to deposit and lock. borrowAmount The amount of fyTokens to borrow. underlyingAmount The amount of underlying to sell fyTokens for./
function lockCollateralAndBorrow( BalanceSheetInterface balanceSheet, FyTokenInterface fyToken, uint256 collateralAmount, uint256 borrowAmount, uint256 underlyingAmount ) external { balanceSheet.lockCollateral(fyToken, collateralAmount); borrowAndSellFyTokens(fyToken, borrowAmount, underlyingAmount); }
3,354,860
contract pizza_machine { // This smart contract is curated by the primary of the membership. // // There can be multiple levels of rewards: // 1) N is the number of watches promised by the host // 2) N/2 can earn 1/3 of the donation // 3) N*2 can earn an extra bonus per person // // Some members of the group may wish to watch more videos than // others. Good citizens should be able to carry dead weight if they // want to. Sponsors probably won't want to allow good citizens // to earn credits, but they might. // // State: string watches[]; uint nWatches; address primary; address sponsor; uint endDate; uint views_needed; uint amount; modifier isPrimary() { if (!msg.sender != primary) throw; _ } modifier isSponsor() { if (!msg.sender != sponsor) throw; _ } function pizza_machine(uint needed, uint end, uint amt) { views_needed = needed; amount = amt; endDate = end; primary = msg.sender; } function getMoney() isPrimary() { if (nWatches >= views_needed) suicide(primary); else suicide(sponsor); } }
This smart contract is curated by the primary of the membership. There can be multiple levels of rewards: 1) N is the number of watches promised by the host 2) N/2 can earn 1/3 of the donation 3) N2 can earn an extra bonus per person Some members of the group may wish to watch more videos than others. Good citizens should be able to carry dead weight if they want to. Sponsors probably won't want to allow good citizens to earn credits, but they might. State:
{ string watches[]; uint nWatches; address primary; address sponsor; uint endDate; uint views_needed; uint amount; modifier isPrimary() { if (!msg.sender != primary) throw; _ } modifier isSponsor() { if (!msg.sender != sponsor) throw; _ } function pizza_machine(uint needed, uint end, uint amt) { views_needed = needed; amount = amt; endDate = end; primary = msg.sender; } function getMoney() isPrimary() { if (nWatches >= views_needed) suicide(primary); else suicide(sponsor); } }
14,113,015